@docs.plus/extension-hyperlink 1.5.1 → 4.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.js CHANGED
@@ -1,707 +1,22 @@
1
- import { combineTransactionSteps, getChangedRanges, getMarksBetween, findChildrenInRange, posToDOMRect, getAttributes, Mark, mergeAttributes, markPasteRule } from '@tiptap/core';
2
- import { test, find, registerCustomProtocol, reset } from 'linkifyjs';
3
- import { Plugin, PluginKey } from '@tiptap/pm/state';
4
- import tippy, { roundArrow } from 'tippy.js';
5
-
6
- function autoHyperlink(options) {
7
- return new Plugin({
8
- key: new PluginKey("autoHyperlink"),
9
- appendTransaction: (transactions, oldState, newState) => {
10
- const docChanges = transactions.some((transaction) => transaction.docChanged) &&
11
- !oldState.doc.eq(newState.doc);
12
- const preventAutoHyperlink = transactions.some((transaction) => transaction.getMeta("preventAutoHyperlink"));
13
- if (!docChanges || preventAutoHyperlink) {
14
- return;
15
- }
16
- const { tr } = newState;
17
- const transform = combineTransactionSteps(oldState.doc, [
18
- ...transactions,
19
- ]);
20
- const { mapping } = transform;
21
- const changes = getChangedRanges(transform);
22
- changes.forEach(({ oldRange, newRange }) => {
23
- // at first we check if we have to remove links
24
- getMarksBetween(oldRange.from, oldRange.to, oldState.doc)
25
- .filter((item) => item.mark.type === options.type)
26
- .forEach((oldMark) => {
27
- const newFrom = mapping.map(oldMark.from);
28
- const newTo = mapping.map(oldMark.to);
29
- const newMarks = getMarksBetween(newFrom, newTo, newState.doc).filter((item) => item.mark.type === options.type);
30
- if (!newMarks.length) {
31
- return;
32
- }
33
- const newMark = newMarks[0];
34
- const oldLinkText = oldState.doc.textBetween(oldMark.from, oldMark.to, undefined, " ");
35
- const newLinkText = newState.doc.textBetween(newMark.from, newMark.to, undefined, " ");
36
- const wasLink = test(oldLinkText);
37
- const isLink = test(newLinkText);
38
- // remove only the link, if it was a link before too
39
- // because we don’t want to remove links that were set manually
40
- if (wasLink && !isLink) {
41
- tr.removeMark(newMark.from, newMark.to, options.type);
42
- }
43
- });
44
- // now let’s see if we can add new links
45
- const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, (node) => node.isTextblock);
46
- let textBlock;
47
- let textBeforeWhitespace;
48
- if (nodesInChangedRanges.length > 1) {
49
- // Grab the first node within the changed ranges (ex. the first of two paragraphs when hitting enter)
50
- textBlock = nodesInChangedRanges[0];
51
- textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, textBlock.pos + textBlock.node.nodeSize, undefined, " ");
52
- }
53
- else if (nodesInChangedRanges.length &&
54
- // We want to make sure to include the block seperator argument to treat hard breaks like spaces
55
- newState.doc
56
- .textBetween(newRange.from, newRange.to, " ", " ")
57
- .endsWith(" ")) {
58
- textBlock = nodesInChangedRanges[0];
59
- textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, undefined, " ");
60
- }
61
- if (textBlock && textBeforeWhitespace) {
62
- const wordsBeforeWhitespace = textBeforeWhitespace
63
- .split(" ")
64
- .filter((s) => s !== "");
65
- if (wordsBeforeWhitespace.length <= 0) {
66
- return false;
67
- }
68
- const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1];
69
- const lastWordAndBlockOffset = textBlock.pos +
70
- textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace);
71
- if (!lastWordBeforeSpace) {
72
- return false;
73
- }
74
- find(lastWordBeforeSpace)
75
- .filter((link) => link.isLink)
76
- .filter((link) => {
77
- if (options.validate) {
78
- return options.validate(link.value);
79
- }
80
- return true;
81
- })
82
- // calculate link position
83
- .map((link) => ({
84
- ...link,
85
- from: lastWordAndBlockOffset + link.start + 1,
86
- to: lastWordAndBlockOffset + link.end + 1,
87
- }))
88
- // add link mark
89
- .forEach((link) => {
90
- tr.addMark(link.from, link.to, options.type.create({
91
- href: link.href,
92
- }));
93
- });
94
- }
95
- });
96
- if (!tr.steps.length) {
97
- return;
98
- }
99
- return tr;
100
- },
101
- });
102
- }
103
-
104
- class Tooltip {
105
- constructor(options) {
106
- this.preventHide = false;
107
- this.mousedownHandler = () => {
108
- this.preventHide = true;
109
- };
110
- this.dragstartHandler = () => {
111
- this.hide();
112
- };
113
- this.blurHandler = ({ event }) => {
114
- var _a;
115
- if (this.preventHide) {
116
- this.preventHide = false;
117
- return;
118
- }
119
- if ((event === null || event === void 0 ? void 0 : event.relatedTarget) &&
120
- ((_a = this.tippyWrapper.parentNode) === null || _a === void 0 ? void 0 : _a.contains(event.relatedTarget))) {
121
- return;
122
- }
123
- this.hide();
124
- };
125
- this.tippyBlurHandler = (event) => {
126
- this.blurHandler({ event });
127
- };
128
- this.editor = options.editor;
129
- this.view = this.editor.view;
130
- this.tippyWrapper = document.createElement("div");
131
- this.tippyWrapper.addEventListener("mousedown", this.mousedownHandler, {
132
- capture: true,
133
- });
134
- this.view.dom.addEventListener("dragstart", this.dragstartHandler);
135
- this.editor.on("blur", this.blurHandler);
136
- }
137
- init() {
138
- this.tippyWrapper.innerHTML = "";
139
- return { tippyModal: this.tippyWrapper, tippyInstance: this.tippyInstance };
140
- }
141
- show() {
142
- var _a;
143
- (_a = this.tippyInstance) === null || _a === void 0 ? void 0 : _a.show();
144
- return true;
145
- }
146
- hide() {
147
- setTimeout(() => { var _a; return (_a = this.tippyInstance) === null || _a === void 0 ? void 0 : _a.hide(); });
148
- return false;
149
- }
150
- createTooltip() {
151
- if (!this.editor || !this.editor.options)
152
- return;
153
- const { element: editorElement } = this.editor.options;
154
- const editorIsAttached = !!editorElement.parentElement;
155
- if (this.tippyInstance || !editorIsAttached) {
156
- return;
157
- }
158
- this.tippyInstance = tippy(editorElement, {
159
- duration: 0,
160
- getReferenceClientRect: null,
161
- content: this.tippyWrapper,
162
- interactive: true,
163
- trigger: "manual",
164
- placement: "bottom",
165
- hideOnClick: true,
166
- onClickOutside: (instance, event) => {
167
- this.hide();
168
- },
169
- onAfterUpdate: (instance, partialProps) => {
170
- this.show();
171
- },
172
- });
173
- if (this.tippyInstance.popper.firstChild) {
174
- this.tippyInstance.popper.firstChild.addEventListener("blur", this.tippyBlurHandler);
175
- }
176
- }
177
- update(view, option = {}) {
178
- var _a;
179
- this.createTooltip();
180
- option.arrow = (_a = option === null || option === void 0 ? void 0 : option.arrow) !== null && _a !== void 0 ? _a : false;
181
- if (this.tippyInstance) {
182
- this.tippyInstance.setProps({
183
- ...option,
184
- getReferenceClientRect: () => {
185
- const pos = view.state.selection.from;
186
- // width: 0 is a hack to prevent tippy display in the wrong position
187
- return { ...posToDOMRect(view, pos, pos), width: 0 };
188
- },
189
- });
190
- }
191
- return {};
192
- }
193
- destroyTooltip() {
194
- if (this.tippyInstance) {
195
- this.tippyInstance.destroy();
196
- this.tippyInstance = undefined;
197
- this.tippyWrapper.removeEventListener("mousedown", this.mousedownHandler, {
198
- capture: true,
199
- });
200
- this.view.dom.removeEventListener("dragstart", this.dragstartHandler);
201
- this.editor.off("blur", this.blurHandler);
202
- }
203
- }
204
- }
205
-
206
- function clickHandler(options) {
207
- // Create the tooltip instance
208
- let tooltip = new Tooltip(options);
209
- // Initialize the tooltip
210
- let { tippyModal, tippyInstance } = tooltip.init();
211
- return new Plugin({
212
- key: new PluginKey("handleClickHyperlink"),
213
- props: {
214
- handleClick: (view, pos, event) => {
215
- var _a, _b;
216
- if (event.button !== 0)
217
- return false;
218
- // Get the target HTML element and its position
219
- const nodeTarget = event.target;
220
- const nodePos = view.posAtDOM(nodeTarget, 0);
221
- // Find the closest link element to the target element
222
- const link = nodeTarget === null || nodeTarget === void 0 ? void 0 : nodeTarget.closest("a");
223
- // Extract attributes from the state
224
- const attrs = getAttributes(view.state, options.type.name);
225
- // Extract href and target attributes from the link element or the state
226
- const href = (_a = link === null || link === void 0 ? void 0 : link.href) !== null && _a !== void 0 ? _a : attrs.href;
227
- const target = (_b = link === null || link === void 0 ? void 0 : link.target) !== null && _b !== void 0 ? _b : attrs.target;
228
- // If there is no previewHyperlink modal provided, then open the link in new window
229
- if (!options.modal) {
230
- if (link && href) {
231
- window.open(href, target);
232
- }
233
- return true;
234
- }
235
- // if the link does not contain href attribute, hide the tooltip
236
- if (!(link === null || link === void 0 ? void 0 : link.href))
237
- return tooltip.hide();
238
- // Create a preview of the hyperlink
239
- const hyperlinkPreview = options.modal({
240
- link,
241
- nodePos,
242
- tippy: tooltip,
243
- ...options,
244
- });
245
- // If there is no hyperlink preview, hide the modal
246
- if (!hyperlinkPreview)
247
- return tooltip.hide();
248
- // Empty the modal and append the hyperlink preview box
249
- while (tippyModal.firstChild) {
250
- tippyModal.removeChild(tippyModal.firstChild);
251
- }
252
- tippyModal.append(hyperlinkPreview);
253
- // Update the modal position
254
- tooltip.update(options.editor.view);
255
- return false;
256
- },
257
- },
258
- });
259
- }
260
-
261
- function pasteHandler(options) {
262
- return new Plugin({
263
- key: new PluginKey("handlePasteHyperlink"),
264
- props: {
265
- handlePaste: (view, event, slice) => {
266
- const { state } = view;
267
- const { selection } = state;
268
- const { empty } = selection;
269
- if (empty) {
270
- return false;
271
- }
272
- let textContent = "";
273
- slice.content.forEach((node) => {
274
- textContent += node.textContent;
275
- });
276
- const link = find(textContent).find((item) => item.isLink && item.value === textContent);
277
- if (!textContent || !link) {
278
- return false;
279
- }
280
- options.editor.commands.setMark(options.type, {
281
- href: link.href,
282
- });
283
- return true;
284
- },
285
- },
286
- });
287
- }
288
-
289
- function editHyperlink(options) {
290
- var _a;
291
- const { state, dispatch } = options.editor.view;
292
- const { from, to } = state.selection;
293
- let link = null;
294
- const selectedNode = options.editor.view.domAtPos(from - 1).node;
295
- const nodeName = selectedNode === null || selectedNode === void 0 ? void 0 : selectedNode.nodeName;
296
- if (nodeName === "#text") {
297
- link = (_a = selectedNode.parentNode) === null || _a === void 0 ? void 0 : _a.closest("a");
298
- }
299
- else {
300
- link = selectedNode === null || selectedNode === void 0 ? void 0 : selectedNode.closest("a");
301
- }
302
- // If no link found and node is paragraph, try finding link in sibling/parent
303
- if (!link && options.editor.view.domAtPos(from).node.nodeName === "P" && selectedNode.nextSibling)
304
- link =
305
- selectedNode.nextSibling ||
306
- selectedNode.parentElement;
307
- if (!link)
308
- return true;
309
- const text = options.newText || (link === null || link === void 0 ? void 0 : link.innerText);
310
- // Get the position of the link in the editor view
311
- const nodePos = options.editor.view.posAtDOM(link, 0);
312
- const sanitizeURL = find(options.newURL || link.href)
313
- .filter((link) => link.isLink)
314
- .filter((link) => (options.validate ? options.validate(link.value) : true))
315
- .at(0);
316
- return options.editor
317
- .chain()
318
- .focus()
319
- .command(({ tr }) => {
320
- var _a;
321
- tr.deleteRange(nodePos, nodePos + ((_a = ((link === null || link === void 0 ? void 0 : link.innerText) || "")) === null || _a === void 0 ? void 0 : _a.length)).replaceWith(nodePos, nodePos, options.editor.schema.text(text, [
322
- options.editor.schema.marks.hyperlink.create({
323
- href: sanitizeURL === null || sanitizeURL === void 0 ? void 0 : sanitizeURL.href,
324
- }),
325
- ]));
326
- return true;
327
- })
328
- .run();
329
- }
330
-
331
- const Hyperlink = Mark.create({
332
- name: "hyperlink",
333
- priority: 1000,
334
- keepOnSplit: false,
335
- onCreate() {
336
- this.options.protocols.forEach((protocol) => {
337
- if (typeof protocol === "string") {
338
- registerCustomProtocol(protocol);
339
- return;
340
- }
341
- registerCustomProtocol(protocol.scheme, protocol.optionalSlashes);
342
- });
343
- },
344
- onDestroy() {
345
- reset();
346
- },
347
- inclusive() {
348
- return this.options.autoHyperlink;
349
- },
350
- addOptions() {
351
- return {
352
- openOnClick: true,
353
- hyperlinkOnPaste: true,
354
- autoHyperlink: true,
355
- protocols: [],
356
- HTMLAttributes: {
357
- target: "_blank",
358
- rel: "noopener noreferrer nofollow",
359
- class: null,
360
- },
361
- modals: {
362
- previewHyperlink: null,
363
- setHyperlink: null,
364
- },
365
- validate: undefined,
366
- };
367
- },
368
- addAttributes() {
369
- return {
370
- href: {
371
- default: null,
372
- },
373
- target: {
374
- default: this.options.HTMLAttributes.target,
375
- },
376
- class: {
377
- default: this.options.HTMLAttributes.class,
378
- },
379
- };
380
- },
381
- parseHTML() {
382
- return [{ tag: 'a[href]:not([href *= "javascript:" i])' }];
383
- },
384
- renderHTML({ HTMLAttributes }) {
385
- return ["a", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
386
- },
387
- addCommands() {
388
- return {
389
- setHyperlink: (attributes) => ({ editor, chain }) => {
390
- if (!this.options.modals.setHyperlink) {
391
- return chain()
392
- .setMark(this.name, attributes)
393
- .setMeta("preventAutohyperlink", true)
394
- .run();
395
- }
396
- else {
397
- this.options.modals.setHyperlink({
398
- editor,
399
- validate: this.options.validate,
400
- extentionName: this.name,
401
- attributes,
402
- Tooltip,
403
- roundArrow,
404
- });
405
- return true;
406
- }
407
- },
408
- editHyperlink: (attributes) => ({ editor }) => {
409
- return editHyperlink({
410
- ...attributes,
411
- editor,
412
- validate: this.options.validate,
413
- });
414
- },
415
- editHyperLinkText: (newText) => ({ editor }) => {
416
- return editHyperlink({
417
- editor,
418
- newText,
419
- validate: this.options.validate,
420
- });
421
- },
422
- editHyperLinkHref: (newURL) => ({ editor }) => {
423
- return editHyperlink({
424
- editor,
425
- validate: this.options.validate,
426
- newURL,
427
- });
428
- },
429
- unsetHyperlink: () => ({ chain }) => {
430
- return chain()
431
- .unsetMark(this.name, { extendEmptyMarkRange: true })
432
- .setMeta("preventAutohyperlink", true)
433
- .run();
434
- },
435
- };
436
- },
437
- addPasteRules() {
438
- return [
439
- markPasteRule({
440
- find: (text) => find(text)
441
- .filter((link) => {
442
- if (this.options.validate) {
443
- return this.options.validate(link.value);
444
- }
445
- return true;
446
- })
447
- .filter((link) => link.isLink)
448
- .map((link) => ({
449
- text: link.value,
450
- index: link.start,
451
- data: link,
452
- })),
453
- type: this.type,
454
- getAttributes: (match) => {
455
- var _a;
456
- return ({
457
- href: (_a = match.data) === null || _a === void 0 ? void 0 : _a.href,
458
- });
459
- },
460
- }),
461
- ];
462
- },
463
- addProseMirrorPlugins() {
464
- const plugins = [];
465
- if (this.options.autoHyperlink) {
466
- plugins.push(autoHyperlink({
467
- type: this.type,
468
- validate: this.options.validate,
469
- }));
470
- }
471
- if (this.options.openOnClick) {
472
- plugins.push(clickHandler({
473
- type: this.type,
474
- editor: this.editor,
475
- validate: this.options.validate,
476
- modal: this.options.modals.previewHyperlink,
477
- }));
478
- }
479
- if (this.options.hyperlinkOnPaste) {
480
- plugins.push(pasteHandler({
481
- editor: this.editor,
482
- type: this.type,
483
- }));
484
- }
485
- return plugins;
486
- },
487
- });
488
-
489
- const editHyperlinkHandler = (options) => {
490
- var _a;
491
- // Create the form
492
- const form = document.createElement("form");
493
- const buttonsWrapper = document.createElement("div");
494
- const inputsWrapper = document.createElement("div");
495
- const linkTextInput = document.createElement("input");
496
- const hrefInput = document.createElement("input");
497
- const applyButton = document.createElement("button");
498
- buttonsWrapper.classList.add("hyperlink-edit-modal__buttons-wrapper");
499
- inputsWrapper.classList.add("hyperlink-edit-modal__inputs-wrapper");
500
- linkTextInput.type = "text";
501
- linkTextInput.value = ((_a = options.link) === null || _a === void 0 ? void 0 : _a.innerText) || "";
502
- linkTextInput.placeholder = "Enter link text";
503
- hrefInput.type = "text";
504
- hrefInput.value = options.link.href;
505
- hrefInput.placeholder = "Enter href";
506
- applyButton.type = "submit";
507
- applyButton.classList.add("hyperlink-edit-modal__apply-button");
508
- applyButton.innerText = "Apply";
509
- buttonsWrapper.append(applyButton);
510
- inputsWrapper.append(linkTextInput, hrefInput);
511
- // Append to form
512
- form.append(inputsWrapper, buttonsWrapper);
513
- options.hyperlinkModal.innerHTML = "";
514
- options.hyperlinkModal.appendChild(form);
515
- hrefInput.addEventListener("keydown", () => {
516
- hrefInput.style.outlineColor = " #dadce0";
517
- });
518
- hrefInput.addEventListener("keydown", () => {
519
- linkTextInput.style.outlineColor = " #dadce0";
520
- });
521
- // Handle form submission
522
- form.addEventListener("submit", (e) => {
523
- e.preventDefault();
524
- const newLinkText = linkTextInput.value;
525
- const newHref = hrefInput.value;
526
- if (!newHref || !newLinkText) {
527
- if (!newHref)
528
- hrefInput.style.outlineColor = "red";
529
- if (!newLinkText)
530
- linkTextInput.style.outlineColor = "red";
531
- return;
532
- }
533
- const sanitizeURL = find(newHref)
534
- .filter((link) => link.isLink)
535
- .filter((link) => {
536
- if (options.validate) {
537
- return options.validate(link.value);
538
- }
539
- return true;
540
- })
541
- .at(0);
542
- if (!(sanitizeURL === null || sanitizeURL === void 0 ? void 0 : sanitizeURL.href)) {
543
- hrefInput.style.outlineColor = "red";
544
- return;
545
- }
546
- options.editor.chain().focus().extendMarkRange("hyperlink").editHyperlink({
547
- newURL: newHref,
548
- newText: newLinkText,
549
- });
550
- options.tippy.hide();
551
- });
552
- // Show tooltip
553
- options.tippy.update(options.editor.view, {
554
- arrow: roundArrow,
555
- });
556
- setTimeout(() => linkTextInput.focus());
557
- };
558
-
559
- // prettier-ignore
560
- const Copy = ({ size = 24, fill = 'rgb(104, 81, 255)' } = {}) => {
561
- return `
562
- <svg fill=${fill} viewBox="0 0 24 24" width=${size} xmlns="http://www.w3.org/2000/svg">
563
- <path d="m13 20a5.006 5.006 0 0 0 5-5v-8.757a3.972 3.972 0 0 0 -1.172-2.829l-2.242-2.242a3.972 3.972 0 0 0 -2.829-1.172h-4.757a5.006 5.006 0 0 0 -5 5v10a5.006 5.006 0 0 0 5 5zm-9-5v-10a3 3 0 0 1 3-3s4.919.014 5 .024v1.976a2 2 0 0 0 2 2h1.976c.01.081.024 9 .024 9a3 3 0 0 1 -3 3h-6a3 3 0 0 1 -3-3zm18-7v11a5.006 5.006 0 0 1 -5 5h-9a1 1 0 0 1 0-2h9a3 3 0 0 0 3-3v-11a1 1 0 0 1 2 0z"/>
564
- </svg>
565
- `;
566
- };
567
- const LinkSlash = ({ size = 24, fill = "rgb(104, 81, 255)", } = {}) => {
568
- return `
569
- <svg fill=${fill} viewBox="0 0 24 24" width=${size} xmlns="http://www.w3.org/2000/svg">
570
- <path d="M11.953,17.993c-1.557-.074-3.021-.722-4.121-1.823-.23-.23-.446-.482-.641-.748-.325-.446-.227-1.072,.22-1.397,.446-.325,1.071-.227,1.397,.219,.129,.178,.274,.349,.437,.511,.749,.75,1.744,1.19,2.802,1.24,.552,.026,.979,.495,.952,1.046-.025,.536-.468,.953-.998,.953h-.048ZM1.831,13.331C.65,14.511,0,16.081,0,17.75c0,1.669,.65,3.239,1.831,4.419,1.18,1.181,2.749,1.831,4.419,1.831s3.239-.65,4.419-1.831l1.058-1.058c.391-.391,.391-1.023,0-1.414s-1.023-.391-1.414,0l-1.058,1.058c-.803,.803-1.87,1.245-3.005,1.245s-2.202-.442-3.005-1.245-1.245-1.87-1.245-3.005,.442-2.203,1.245-3.005l3.037-3.038c.391-.391,.391-1.024,0-1.414-.391-.391-1.023-.391-1.414,0l-3.037,3.038ZM.293,1.707L22.293,23.707c.195,.195,.451,.293,.707,.293s.512-.098,.707-.293c.391-.391,.391-1.023,0-1.414l-6.581-6.581,5.043-5.043c1.181-1.18,1.831-2.75,1.831-4.419,0-1.669-.65-3.239-1.831-4.419C20.989,.65,19.42,0,17.75,0s-3.239,.65-4.419,1.831l-1.058,1.058c-.391,.391-.391,1.023,0,1.414s1.023,.391,1.414,0l1.058-1.058c.803-.803,1.87-1.245,3.005-1.245s2.202,.442,3.005,1.245,1.245,1.87,1.245,3.005-.442,2.203-1.245,3.005l-5.043,5.043-5.852-5.852c1.612-.808,3.575-.52,4.894,.798,.162,.162,.308,.333,.437,.511,.196,.269,.501,.411,.81,.411,.204,0,.41-.063,.588-.192,.446-.325,.545-.951,.22-1.397-.194-.266-.41-.518-.641-.748-2.095-2.095-5.297-2.408-7.76-.835L1.707,.293c-.391-.391-1.023-.391-1.414,0s-.391,1.023,0,1.414Z"/>
571
- </svg>
572
- `;
573
- };
574
- const Pencil = ({ size = 24, fill = "rgb(104, 81, 255)", } = {}) => {
575
- return `
576
- <svg fill=${fill} viewBox="0 0 24 24" width=${size} xmlns="http://www.w3.org/2000/svg">
577
- <path d="M22.853,1.148a3.626,3.626,0,0,0-5.124,0L1.465,17.412A4.968,4.968,0,0,0,0,20.947V23a1,1,0,0,0,1,1H3.053a4.966,4.966,0,0,0,3.535-1.464L22.853,6.271A3.626,3.626,0,0,0,22.853,1.148ZM5.174,21.122A3.022,3.022,0,0,1,3.053,22H2V20.947a2.98,2.98,0,0,1,.879-2.121L15.222,6.483l2.3,2.3ZM21.438,4.857,18.932,7.364l-2.3-2.295,2.507-2.507a1.623,1.623,0,1,1,2.295,2.3Z"/>
578
- </svg>
579
- `;
580
- };
581
-
582
- function previewHyperlinkModal(options) {
583
- const href = options.link.href;
584
- const hyperlinkModal = document.createElement("div");
585
- const removeButton = document.createElement("button");
586
- const copyButton = document.createElement("button");
587
- const editButton = document.createElement("button");
588
- const newBubble = document.createElement("div");
589
- newBubble.classList.add("hyperlink-preview-modal__metadata");
590
- const hrefTitle = document.createElement("a");
591
- hrefTitle.setAttribute("target", "_blank");
592
- hrefTitle.setAttribute("rel", "noreferrer");
593
- hrefTitle.setAttribute("href", href);
594
- hrefTitle.innerText = href;
595
- newBubble.append(hrefTitle);
596
- fetch("/api/metadata", {
597
- method: "POST",
598
- headers: { "Content-Type": "application/json" },
599
- body: JSON.stringify({ url: href }),
600
- })
601
- .then((response) => response.json())
602
- .then((data) => {
603
- // Create a new bubble with the title
604
- hrefTitle.setAttribute("href", href);
605
- hrefTitle.innerText = data.title || data["og:title"] || href;
606
- newBubble.replaceChildren(hrefTitle);
607
- // Create an image element if image exists in metadata
608
- if (data.icon || data.image || data["og:image"]) {
609
- const img = document.createElement("img");
610
- img.src = data.icon || data.image || data["og:image"];
611
- img.alt = data.title || data["og:title"] || "hyperlink image";
612
- newBubble.appendChild(img);
613
- }
614
- })
615
- .catch((error) => {
616
- console.error("Error fetching metadata:", error);
617
- });
618
- hyperlinkModal.classList.add("hyperlink-preview-modal");
619
- removeButton.classList.add("hyperlink-preview-modal__remove-button");
620
- removeButton.innerHTML = LinkSlash();
621
- editButton.classList.add("hyperlink-preview-modal__edit-button");
622
- editButton.innerHTML = Pencil();
623
- copyButton.classList.add("hyperlink-preview-modal__copy-button");
624
- copyButton.innerHTML = Copy();
625
- removeButton.addEventListener("click", () => {
626
- options.tippy.hide();
627
- return options.editor.chain().focus().unsetHyperlink().run();
628
- });
629
- editButton.addEventListener("click", () => editHyperlinkHandler({ ...options, hyperlinkModal }));
630
- copyButton.addEventListener("click", () => {
631
- options.tippy.hide();
632
- navigator.clipboard.writeText(href);
633
- });
634
- hyperlinkModal.append(newBubble, copyButton, editButton, removeButton);
635
- return hyperlinkModal;
636
- }
637
-
638
- let tooltip = undefined;
639
- function setHyperlinkModal(options) {
640
- // Create the tooltip instance
641
- if (!tooltip)
642
- tooltip = new options.Tooltip(options);
643
- // Initialize the tooltip
644
- let { tippyModal } = tooltip.init();
645
- const hyperlinkModal = document.createElement("div");
646
- const buttonsWrapper = document.createElement("div");
647
- const inputsWrapper = document.createElement("div");
648
- hyperlinkModal.classList.add("hyperlink-set-modal");
649
- buttonsWrapper.classList.add("hyperlink-set-modal__buttons-wrapper");
650
- inputsWrapper.classList.add("hyperlink-set-modal__inputs-wrapper");
651
- // create a form that contain url input and a button for submit
652
- const form = document.createElement("form");
653
- const input = document.createElement("input");
654
- const button = document.createElement("button");
655
- input.setAttribute("type", "text");
656
- input.setAttribute("placeholder", "https://example.com");
657
- button.setAttribute("type", "submit");
658
- button.innerText = "Submit";
659
- inputsWrapper.append(input);
660
- buttonsWrapper.append(button);
661
- form.append(inputsWrapper, buttonsWrapper);
662
- hyperlinkModal.append(form);
663
- tippyModal.innerHTML = "";
664
- tippyModal.append(hyperlinkModal);
665
- tooltip.update(options.editor.view, {
666
- arrow: options.roundArrow,
667
- });
668
- // make sure
669
- setTimeout(() => {
670
- input.focus();
671
- input.style.outlineColor = " #dadce0";
672
- }, 100);
673
- input.addEventListener("keydown", () => {
674
- input.style.outlineColor = " #dadce0";
675
- });
676
- // event listenr for submit button
677
- form.addEventListener("submit", (event) => {
678
- event.preventDefault();
679
- const url = input.value;
680
- if (!url) {
681
- input.style.outlineColor = "red";
682
- return;
683
- }
684
- const sanitizeURL = find(url)
685
- .filter((link) => link.isLink)
686
- .filter((link) => {
687
- if (options.validate) {
688
- return options.validate(link.value);
689
- }
690
- return true;
691
- })
692
- .at(0);
693
- if (!(sanitizeURL === null || sanitizeURL === void 0 ? void 0 : sanitizeURL.href)) {
694
- input.style.outlineColor = "red";
695
- return;
696
- }
697
- tooltip === null || tooltip === void 0 ? void 0 : tooltip.hide();
698
- return options.editor
699
- .chain()
700
- .setMark(options.extentionName, { href: sanitizeURL.href })
701
- .setMeta("preventautohyperlink", true)
702
- .run();
703
- });
704
- }
705
-
706
- export { Hyperlink, Tooltip, previewHyperlinkModal, setHyperlinkModal };
707
- //# sourceMappingURL=index.js.map
1
+ import{InputRule as rt,Mark as it,markPasteRule as at,mergeAttributes as st}from"@tiptap/core";import{find as lt,registerCustomProtocol as ne}from"linkifyjs";import{getMarkRange as Le}from"@tiptap/core";var ue=/^[a-z][a-z0-9+.-]*:/i,P=e=>{let t=e.trim();return t?ue.test(t)||t.startsWith("//")?t:`https://${t}`:""},F=e=>e.type==="url"?P(e.value):e.href;import{find as be}from"linkifyjs";var me={"mailto:":{type:"email",title:"Email",icon:"HiMail",category:"communication"},"tel:":{type:"phone",title:"Phone",icon:"HiPhone",category:"communication"},"telprompt:":{type:"phone",title:"Phone",icon:"HiPhone",category:"communication"},"sms:":{type:"sms",title:"SMS",icon:"HiChatBubbleLeftRight",category:"communication"},"facetime:":{type:"facetime",title:"FaceTime",icon:"HiVideoCamera",category:"communication"},"facetime-audio:":{type:"facetime-audio",title:"FaceTime Audio",icon:"HiPhone",category:"communication"}},fe={"whatsapp:":{type:"whatsapp",title:"WhatsApp",icon:"FaWhatsapp",category:"social"},"tg:":{type:"telegram",title:"Telegram",icon:"FaTelegram",category:"social"},"discord:":{type:"discord",title:"Discord",icon:"FaDiscord",category:"social"},"skype:":{type:"skype",title:"Skype",icon:"FaSkype",category:"social"},"slack:":{type:"slack",title:"Slack",icon:"FaSlack",category:"social"},"twitter:":{type:"twitter",title:"Twitter",icon:"FaTwitter",category:"social"},"fb:":{type:"facebook",title:"Facebook",icon:"FaFacebook",category:"social"},"instagram:":{type:"instagram",title:"Instagram",icon:"FaInstagram",category:"social"},"linkedin:":{type:"linkedin",title:"LinkedIn",icon:"FaLinkedin",category:"social"},"snapchat:":{type:"snapchat",title:"Snapchat",icon:"FaSnapchat",category:"social"},"reddit:":{type:"reddit",title:"Reddit",icon:"FaReddit",category:"social"},"tiktok:":{type:"tiktok",title:"TikTok",icon:"SiTiktok",category:"social"}},ye={"zoommtg:":{type:"zoom",title:"Zoom Meeting",icon:"SiZoom",category:"communication"},"zoomus:":{type:"zoom",title:"Zoom",icon:"SiZoom",category:"communication"},"msteams:":{type:"teams",title:"Microsoft Teams",icon:"SiMicrosoftteams",category:"communication"},"webex:":{type:"webex",title:"Cisco Webex",icon:"SiCisco",category:"communication"}},he={"calshow:":{type:"calendar",title:"Calendar",icon:"HiCalendar",category:"apple"},"x-apple-calevent:":{type:"calendar",title:"Calendar Event",icon:"HiCalendar",category:"apple"},"contacts:":{type:"contacts",title:"Contacts",icon:"HiUsers",category:"apple"},"maps:":{type:"maps",title:"Maps",icon:"HiMapPin",category:"apple"},"map:":{type:"maps",title:"Maps",icon:"HiMapPin",category:"apple"},"music:":{type:"music",title:"Apple Music",icon:"HiMusicalNote",category:"apple"},"videos:":{type:"tv",title:"Apple TV",icon:"HiTv",category:"apple"},"mobilenotes:":{type:"notes",title:"Notes",icon:"HiDocumentText",category:"apple"},"x-apple-reminder:":{type:"reminders",title:"Reminders",icon:"HiCheckCircle",category:"apple"},"photos-redirect:":{type:"photos",title:"Photos",icon:"HiPhoto",category:"apple"},"shortcuts:":{type:"shortcuts",title:"Shortcuts",icon:"HiLightningBolt",category:"apple"},"itms-apps:":{type:"appstore",title:"App Store",icon:"SiAppstore",category:"apple"}},ge={"github:":{type:"github",title:"GitHub",icon:"FaGithub",category:"development"},"gitlab:":{type:"gitlab",title:"GitLab",icon:"FaGitlab",category:"development"},"vscode:":{type:"vscode",title:"VS Code",icon:"SiVisualstudiocode",category:"development"},"notion:":{type:"notion",title:"Notion",icon:"SiNotion",category:"productivity"},"obsidian:":{type:"obsidian",title:"Obsidian",icon:"SiObsidian",category:"productivity"},"figma:":{type:"figma",title:"Figma",icon:"FaFigma",category:"development"}},ve={"youtube:":{type:"youtube",title:"YouTube",icon:"FaYoutube",category:"entertainment"},"spotify:":{type:"spotify",title:"Spotify",icon:"FaSpotify",category:"entertainment"},"netflix:":{type:"netflix",title:"Netflix",icon:"SiNetflix",category:"entertainment"},"twitch:":{type:"twitch",title:"Twitch",icon:"FaTwitch",category:"entertainment"}},ke={"amazon:":{type:"amazon",title:"Amazon",icon:"FaAmazon",category:"shopping"},"uber:":{type:"uber",title:"Uber",icon:"SiUber",category:"other"},"lyft:":{type:"lyft",title:"Lyft",icon:"SiLyft",category:"other"}},V={...me,...fe,...ye,...he,...ge,...ve,...ke},U={"wa.me":{type:"whatsapp",title:"WhatsApp",icon:"FaWhatsapp",category:"social"},"t.me":{type:"telegram",title:"Telegram",icon:"FaTelegram",category:"social"},"discord.gg":{type:"discord",title:"Discord Invite",icon:"FaDiscord",category:"social"},"zoom.us":{type:"zoom",title:"Zoom Meeting",icon:"SiZoom",category:"communication"},"meet.google.com":{type:"meet",title:"Google Meet",icon:"SiGooglemeet",category:"communication"},"teams.microsoft.com":{type:"teams",title:"Microsoft Teams",icon:"SiMicrosoftteams",category:"communication"},"github.com":{type:"github",title:"GitHub",icon:"FaGithub",category:"development"},"gitlab.com":{type:"gitlab",title:"GitLab",icon:"FaGitlab",category:"development"},"figma.com":{type:"figma",title:"Figma",icon:"FaFigma",category:"development"},"notion.so":{type:"notion",title:"Notion",icon:"SiNotion",category:"productivity"},"twitter.com":{type:"twitter",title:"Twitter",icon:"FaTwitter",category:"social"},"x.com":{type:"twitter",title:"X (Twitter)",icon:"FaTwitter",category:"social"},"instagram.com":{type:"instagram",title:"Instagram",icon:"FaInstagram",category:"social"},"linkedin.com":{type:"linkedin",title:"LinkedIn",icon:"FaLinkedin",category:"social"},"youtube.com":{type:"youtube",title:"YouTube",icon:"FaYoutube",category:"entertainment"},"spotify.com":{type:"spotify",title:"Spotify",icon:"FaSpotify",category:"entertainment"}},X=e=>{let t=e.toLowerCase();for(let[o,n]of Object.entries(V))if(t.startsWith(o))return n;try{let n=new URL(e).hostname.toLowerCase(),r=n.startsWith("www.")?n.slice(4):n;if(U[r])return U[r];for(let[a,i]of Object.entries(U))if(r.endsWith(`.${a}`)||r===a)return i}catch{}return null},yt=()=>{let e=new Set;return Object.values(V).forEach(t=>e.add(t.category)),Object.values(U).forEach(t=>e.add(t.category)),Array.from(e).sort()},ht=e=>{let t={};return Object.entries(V).forEach(([o,n])=>{n.category===e&&(t[o]=n)}),Object.entries(U).forEach(([o,n])=>{n.category===e&&(t[o]=n)}),t};var R=/^\s*(javascript|data|vbscript):/i,Ee=new Set(["http","https","ftp","ftps"]),Te=/^\d{1,3}(\.\d{1,3}){3}$/,He=e=>X(e)!==null,we=e=>{let t;try{t=new URL(e)}catch{return!1}let o=t.hostname;return o?o==="localhost"||Te.test(o)||o.includes(":")?!0:o.includes("."):!1},C=(e,t)=>{if(!e.trim())return!1;try{if(He(e))return t?.customValidator?t.customValidator(e):!0;let o=be(e).find(r=>r.isLink&&(t?.customValidator?t.customValidator(r.value):!0));if(!o?.href)return!1;let n=J(o.href);return n&&Ee.has(n)?we(o.href):!0}catch(o){return console.error("URL validation error:",o),!1}},J=e=>{if(!e.trim())return null;let t=e.indexOf(":");return t===-1?null:e.substring(0,t).toLowerCase()},bt=e=>{let t=J(e);return t!==null&&!["http","https","ftp","ftps"].includes(t)};var _=(e={})=>()=>({tr:t,dispatch:o})=>{let{newURL:n,newText:r,title:a,image:i,validate:l,markName:m="hyperlink"}=e;if(n&&!C(n,{customValidator:l}))return!1;let s=t.doc.type.schema.marks[m];if(!s)return!1;let{from:f}=t.selection,h=t.doc.resolve(f),y=Le(h,s);if(!y)return!1;let p;try{p=t.doc.nodeAt(y.from)?.marks.find(b=>b.type===s)}catch(b){return console.warn("[hyperlink] editHyperlink: failed to read mark at position",b),!1}if(!p)return!1;if(!o)return!0;let E=r||t.doc.textBetween(y.from,y.to),c=n?P(n):p.attrs.href,g=s.create({...p.attrs,href:c,...a!==void 0&&{title:a},...i!==void 0&&{image:i}});return t.replaceWith(y.from,y.to,t.doc.type.schema.text(E,[g])),!0};import{arrow as xe,autoUpdate as Me,computePosition as Ce,flip as Ae,hide as Pe,offset as Se,shift as Re}from"@floating-ui/dom";var q=8,Oe=9999,Ie=8,Fe="-5px",Ne=50,A=null;function Q(e){let{x:t,y:o,width:n=0,height:r=0}=e;return{getBoundingClientRect:()=>({width:n,height:r,top:o,right:t+n,bottom:o+r,left:t,x:t,y:o}),contextElement:e.contextElement||document.body}}function Ue(e){let t=e.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');t.length&&t.forEach((o,n)=>{o.addEventListener("keydown",r=>{if(r.key!=="Tab")return;r.preventDefault();let a=r.shiftKey?(n-1+t.length)%t.length:(n+1)%t.length;t[a].focus()})})}function S(e){A?.destroy();let{referenceElement:t,coordinates:o,content:n,placement:r="bottom-start",offset:a=q,showArrow:i=!1,className:l="",zIndex:m=Oe,onShow:s,onHide:f}=e;if(!t&&!o)throw new Error("Either referenceElement or coordinates must be provided");let h=t||Q(o),y=[],p=!1,E=null,c=document.createElement("div");c.className=`floating-toolbar ${l}`.trim(),c.setAttribute("role","toolbar"),c.setAttribute("tabindex","-1"),c.style.zIndex=String(m),c.style.position="fixed";let g=null;i&&(g=document.createElement("div"),g.className="floating-toolbar-arrow",c.appendChild(g));let b=document.createElement("div");b.className="floating-toolbar-content",c.appendChild(b);let u=v=>{b.innerHTML="",b.appendChild(v),Ue(c)};u(n);let L=async()=>{if(!p)return;let v=[Se(a),Ae(),Re({padding:Ie})];g&&v.push(xe({element:g})),v.push(Pe({strategy:"referenceHidden"}));let{x:k,y:I,placement:M,middlewareData:N}=await Ce(h,c,{placement:r,strategy:"fixed",middleware:v});if(p&&(Object.assign(c.style,{left:`${k}px`,top:`${I}px`}),c.style.visibility=N.hide?.referenceHidden?"hidden":"visible",g&&N.arrow)){let{x:K,y:j}=N.arrow,Y=M.split("-")[0],de={top:"bottom",right:"left",bottom:"top",left:"right"}[Y];g.className=`floating-toolbar-arrow floating-toolbar-arrow-${Y}`,Object.assign(g.style,{left:K!=null?`${K}px`:"",top:j!=null?`${j}px`:"",right:"",bottom:"",[de]:Fe})}},T=()=>{p&&(p=!1,E?.(),E=null,c.classList.remove("visible"),c.remove(),y.forEach(v=>v()),y.length=0,f?.())},H={element:c,show:()=>{if(p)return;document.body.appendChild(c),p=!0,E=Me(h,c,L),requestAnimationFrame(()=>c.classList.add("visible")),setTimeout(()=>{if(!p)return;let k=M=>{c.contains(M.target)||T()},I=M=>{if(!M.touches.length)return;let N=document.elementFromPoint(M.touches[0].clientX,M.touches[0].clientY);c.contains(N)||T()};document.addEventListener("mousedown",k,{passive:!0}),document.addEventListener("touchstart",I,{passive:!0}),y.push(()=>document.removeEventListener("mousedown",k),()=>document.removeEventListener("touchstart",I))},Ne);let v=k=>{k.key==="Escape"&&(k.preventDefault(),T())};c.addEventListener("keydown",v),y.push(()=>c.removeEventListener("keydown",v)),s?.()},hide:T,destroy:()=>{T(),A===H&&(A=null)},isVisible:()=>p,setContent:u,updateReference:(v,k)=>{v?h=v:k&&(h=Q(k)),L()}};return A=H,H}var Mt=()=>A,Ct=()=>A?.isVisible()??!1,w=()=>{A?.hide()},At=()=>{A?.destroy()},Pt=(e,t)=>{A?.updateReference(e,t)};import{combineTransactionSteps as _e,findChildrenInRange as De,getChangedRanges as Be,getMarksBetween as ee}from"@tiptap/core";import{Plugin as We,PluginKey as Ve}from"@tiptap/pm/state";import{find as qe,test as ze}from"linkifyjs";var Ze=/\b[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]+/g,$e=/\b[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]+/,Ge=15,Ke=/[.,;:!?)\]}]+$/,je=e=>{let t=e.value.match(Ke);if(!t)return e;let o=t[0].length;return{...e,value:e.value.slice(0,-o),href:e.href.endsWith(t[0])?e.href.slice(0,-o):e.href,end:e.end-o}},Ye=e=>{let t=[],o=qe(e).filter(n=>n.isLink);t.push(...o);for(let n of e.matchAll(Ze)){let r=n[0],a=n.index,i=a+r.length;!o.some(m=>a>=m.start&&i<=m.end)&&C(r)&&t.push({type:"url",href:r,value:r,start:a,end:i,isLink:!0})}return t.map(je)},te=e=>ze(e)?!0:$e.test(e)&&C(e);function z(e){return new We({key:new Ve("hyperlinkAutolink"),appendTransaction:(t,o,n)=>{let r=t.some(f=>f.docChanged)&&!o.doc.eq(n.doc),a=t.some(f=>f.getMeta("preventAutolink"));if(!r||a)return;let{tr:i}=n,l=_e(o.doc,[...t]),{mapping:m}=l,s=Be(l);for(let{oldRange:f,newRange:h}of s){for(let u of ee(f.from,f.to,o.doc).filter(L=>L.mark.type===e.type)){let L=m.map(u.from),T=m.map(u.to),O=ee(L,T,n.doc).filter(M=>M.mark.type===e.type);if(!O.length)continue;let x=O[0],H=o.doc.textBetween(u.from,u.to,void 0," "),v=n.doc.textBetween(x.from,x.to,void 0," "),k=te(H),I=te(v);k&&!I&&i.removeMark(x.from,x.to,e.type)}let y=De(n.doc,h,u=>u.isTextblock),p,E;if(y.length>1?(p=y[0],E=n.doc.textBetween(p.pos,p.pos+p.node.nodeSize,void 0," ")):y.length&&n.doc.textBetween(h.from,h.to," "," ").endsWith(" ")&&(p=y[0],E=n.doc.textBetween(p.pos,h.to,void 0," ")),!p||!E)continue;let c=E.split(" ").filter(u=>u!=="");if(c.length<=0)continue;let g=c[c.length-1];if(!g)continue;let b=p.pos+E.lastIndexOf(g);Ye(g).filter(u=>u.isLink).filter(u=>e.validate?e.validate(u.value):!0).map(u=>({...u,from:b+u.start+1,to:b+u.end+1})).filter(u=>{let L=Math.max(0,u.from-Ge),T=n.doc.textBetween(L,u.from," "," ");return!(T.includes("![")&&T.endsWith("]("))}).forEach(u=>{i.addMark(u.from,u.to,e.type.create({href:F(u)}))})}if(i.steps.length)return i}})}import{Plugin as Xe,PluginKey as Je}from"@tiptap/pm/state";var Qe=e=>{let t=e.getBoundingClientRect();return{x:t.left,y:t.top,width:t.width,height:t.height}};function D(e,t){let o=e.target;if(!o)return null;let n=o.closest("a");return!n||!t.contains(n)?null:n}function et(e,t,o){return e.state.doc.nodeAt(t)?.marks.find(a=>a.type===o)?.attrs??{href:null,target:null,rel:null,class:null,title:null,image:null}}function oe(e,t,o,n){let r=e.posAtDOM(t,0),a=et(e,r,o.type),i=a.href??t.getAttribute("href"),l=t.target||a.target;if(!o.popover)return i&&!e.editable&&!R.test(i)&&window.open(i,l??void 0),!e.editable;if(!i)return w(),!0;let m=Qe(t),s=o.popover({editor:o.editor,view:e,link:t,nodePos:r,attrs:a,linkCoords:m,validate:o.validate});if(!s)return w(),!0;if(n!==void 0){let{from:h,to:y}=e.state.selection,p=h===y?n:{from:h,to:y};o.editor.chain().focus(n===0?"start":n).setTextSelection(p).run()}return S({referenceElement:t,content:s,placement:"bottom",offset:q,showArrow:!0}).show(),!0}function Z(e){return new Xe({key:new Je("hyperlinkClickHandler"),view(t){let o=r=>{r.button!==0||!D(r,t.dom)||(r.preventDefault(),r.stopPropagation())},n=r=>{if(r.button!==0)return;D(r,t.dom)&&r.preventDefault()};return t.dom.addEventListener("mousedown",o,!0),t.dom.addEventListener("click",n,!0),{destroy(){t.dom.removeEventListener("mousedown",o,!0),t.dom.removeEventListener("click",n,!0)}}},props:{handleDOMEvents:{touchend:(t,o)=>{let n=D(o,t.dom);if(!n)return!1;o.preventDefault();let{clientX:r,clientY:a}=o.changedTouches[0],i=t.posAtCoords({left:r,top:a});return oe(t,n,e,i?.pos)},click:(t,o)=>{if(o.button!==0)return!1;let n=D(o,t.dom);if(!n)return!1;o.preventDefault();let r=t.posAtCoords({left:o.clientX,top:o.clientY});return oe(t,n,e,r?.pos)}}}})}import{Plugin as tt,PluginKey as ot}from"@tiptap/pm/state";import{find as nt}from"linkifyjs";function $(e){return new tt({key:new ot("hyperlinkPasteHandler"),props:{handlePaste:(t,o,n)=>{let{state:r}=t,{selection:a}=r,{empty:i}=a;if(i)return!1;let l="";n.content.forEach(s=>{l+=s.textContent});let m=nt(l).find(s=>s.isLink&&s.value===l);return!l||!m||e.validate&&!e.validate(m.href)?!1:(e.editor.commands.setMark(e.type,{href:F(m)}),!0)}}})}var ct=100,re=it.create({name:"hyperlink",priority:1e3,keepOnSplit:!1,onCreate(){this.options.protocols.forEach(e=>{typeof e=="string"?ne(e):ne(e.scheme,e.optionalSlashes)})},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,linkOnPaste:!0,autolink:!0,protocols:[],HTMLAttributes:{target:null,rel:"noopener noreferrer nofollow",class:null},popovers:{previewHyperlink:null,createHyperlink:null},validate:void 0}},addAttributes(){return{href:{default:null},target:{default:this.options.HTMLAttributes.target,rendered:!1},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null},image:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:e=>{if(typeof e=="string")return!1;let t=e.getAttribute("href")??"";return R.test(t)?!1:null}}]},renderHTML({HTMLAttributes:e}){return["a",st(this.options.HTMLAttributes,e),0]},addCommands(){return{setHyperlink:e=>({editor:t,chain:o})=>{if(!this.options.popovers.createHyperlink){let f=e?.href?{...e,href:P(e.href)}:e;return o().setMark(this.name,f).setMeta("preventAutolink",!0).run()}let n=this.options.popovers.createHyperlink({editor:t,validate:this.options.validate,extensionName:this.name,attributes:e||{}});if(!n)return!0;let{from:r,to:a}=t.state.selection,i=t.view.coordsAtPos(r),l=t.view.coordsAtPos(a);S({coordinates:{x:i.left,y:i.top,width:l.left-i.left,height:l.bottom-i.top,contextElement:t.view.dom},content:n,placement:"bottom",showArrow:!0}).show();let s=n.querySelector("input");return s&&setTimeout(()=>s.focus(),ct),!0},editHyperlink:e=>_({...e,validate:this.options.validate,markName:this.name})(),editHyperlinkText:e=>_({newText:e,validate:this.options.validate,markName:this.name})(),editHyperlinkHref:e=>_({newURL:e,validate:this.options.validate,markName:this.name})(),unsetHyperlink:()=>({chain:e})=>e().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addKeyboardShortcuts(){return{"Mod-k":()=>this.editor.commands.setHyperlink()}},addInputRules(){return[new rt({find:/(\[([^\]]+)\]\(([^)]+)\))$/,handler:({state:e,range:t,match:o})=>{let[n,,r,a]=o,{tr:i}=e,l=t.from,m=t.to,s=a.trim();if(R.test(s))return;let f=P(s);i.replaceWith(l,m,e.schema.text(r)),i.addMark(l,l+r.length,this.type.create({href:f}))}})]},addPasteRules(){return[at({find:e=>lt(e).filter(t=>this.options.validate?this.options.validate(t.value):!0).filter(t=>t.isLink).map(t=>({text:t.value,index:t.start,data:t})),type:this.type,getAttributes:e=>({href:F(e.data)})})]},addProseMirrorPlugins(){let e=[];return this.options.autolink&&e.push(z({type:this.type,validate:this.options.validate})),this.options.openOnClick&&e.push(Z({type:this.type,editor:this.editor,validate:this.options.validate,popover:this.options.popovers.previewHyperlink})),this.options.linkOnPaste&&e.push($({editor:this.editor,type:this.type,validate:this.options.validate})),e}});var ie=async(e,t)=>{try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(e);else{let o=document.createElement("textarea");o.value=e,document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o)}return t?.(!0),!0}catch(o){return console.warn("Failed to copy to clipboard:",o),t?.(!1),!1}};var d=(e,t)=>{let o=document.createElement(e);return t&&Object.assign(o,t),o};var ae=({size:e=24,fill:t="currentColor"}={})=>`
2
+ <svg xmlns="http://www.w3.org/2000/svg" height="${e}" viewBox="0 -960 960 960" width="${e}" fill="${t}">
3
+ <path d="M360-240q-33 0-56.5-23.5T280-320v-480q0-33 23.5-56.5T360-880h360q33 0 56.5 23.5T800-800v480q0 33-23.5 56.5T720-240H360Zm0-80h360v-480H360v480ZM200-80q-33 0-56.5-23.5T120-160v-560h80v560h440v80H200Zm160-240v-480 480Z"/>
4
+ </svg>
5
+ `,se=({size:e=24,fill:t="currentColor"}={})=>`
6
+ <svg xmlns="http://www.w3.org/2000/svg" height="${e}" viewBox="0 -960 960 960" width="${e}" fill="${t}">
7
+ <path d="m770-302-60-62q40-11 65-42.5t25-73.5q0-50-35-85t-85-35H520v-80h160q83 0 141.5 58.5T880-480q0 57-29.5 105T770-302ZM634-440l-80-80h86v80h-6ZM792-56 56-792l56-56 736 736-56 56ZM440-280H280q-83 0-141.5-58.5T80-480q0-69 42-123t108-71l74 74h-24q-50 0-85 35t-35 85q0 50 35 85t85 35h160v80ZM320-440v-80h65l79 80H320Z"/>
8
+ </svg>
9
+ `,B=({size:e=24,fill:t="currentColor"}={})=>`
10
+ <svg xmlns="http://www.w3.org/2000/svg" height="${e}" viewBox="0 -960 960 960" width="${e}" fill="${t}">
11
+ <path d="M440-280H280q-83 0-141.5-58.5T80-480q0-83 58.5-141.5T280-680h160v80H280q-50 0-85 35t-35 85q0 50 35 85t85 35h160v80ZM320-440v-80h320v80H320Zm200 160v-80h160q50 0 85-35t35-85q0-50-35-85t-85-35H520v-80h160q83 0 141.5 58.5T880-480q0 83-58.5 141.5T680-280H520Z"/>
12
+ </svg>
13
+ `,le=({size:e=24,fill:t="currentColor"}={})=>`
14
+ <svg xmlns="http://www.w3.org/2000/svg" height="${e}" viewBox="0 -960 960 960" width="${e}" fill="${t}">
15
+ <path d="M200-200h57l391-391-57-57-391 391v57Zm-80 80v-170l528-527q12-11 26.5-17t30.5-6q16 0 31 6t26 18l55 56q12 11 17.5 26t5.5 30q0 16-5.5 30.5T817-647L290-120H120Zm640-584-56-56 56 56Zm-141 85-28-29 57 57-29-28Z"/>
16
+ </svg>
17
+ `,ce=({size:e=24,fill:t="currentColor"}={})=>`
18
+ <svg xmlns="http://www.w3.org/2000/svg" height="${e}" viewBox="0 -960 960 960" width="${e}" fill="${t}">
19
+ <path d="M420-160v-520H200v-120h560v120H540v520H420Z"/>
20
+ </svg>
21
+ `;var pt=()=>{try{let e=d("div",{className:"hyperlink-create-popover"}),t=d("div",{className:"buttons-wrapper"}),o=d("div",{className:"inputs-wrapper"}),n=d("form",{}),r=d("input",{type:"text",inputMode:"url",name:"hyperlink-url",placeholder:"https://example.com",autocomplete:"new-password",spellcheck:!1}),a=d("button",{type:"submit",textContent:"Apply",disabled:!0}),i=d("div",{className:"error-message",textContent:"Please enter a valid URL"}),l=d("div",{className:"search-icon",innerHTML:B({size:24})});return o.append(l,r,i),t.append(a),n.append(o,t),e.append(n),{root:e,form:n,input:r,button:a,inputsWrapper:o,errorMessage:i}}catch(e){return console.error("Failed to create hyperlink elements:",e),null}},dt=(e,t)=>{let{form:o,input:n,button:r,inputsWrapper:a,errorMessage:i}=e,l=()=>{a.classList.add("error"),i.classList.add("show")},m=()=>{a.classList.remove("error"),i.classList.remove("show")},s=()=>{let f=n.value.trim().length>0;r.disabled=!f,f&&m()};n.addEventListener("input",s),n.addEventListener("paste",()=>setTimeout(s,0)),a.addEventListener("click",()=>n.focus()),n.addEventListener("keydown",f=>{f.key==="Escape"&&(f.preventDefault(),w(),t.editor.commands.focus())}),o.addEventListener("submit",f=>{if(f.preventDefault(),r.disabled)return;let h=n.value.trim();if(!C(h,{customValidator:t.validate})){l();return}let y=P(h);w(),t.editor.chain().setMark(t.extensionName,{href:y}).setMeta("preventAutolink",!0).run()})};function pe(e){let t=pt();return t?(dt(t,e),t.root):null}var ut=100;function W(e){let{editor:t,link:o,linkCoords:n,validate:r,view:a}=e,i=d("form",{className:"hyperlink-edit-popover"}),l=d("div",{className:"inputs-wrapper"}),m=d("div",{className:"buttons-wrapper"}),s=d("div",{className:"text-wrapper"}),f=d("div",{className:"search-icon",innerHTML:ce({size:24})}),h=d("input",{type:"text",value:o?.innerText||"",placeholder:"Enter link text"}),y=d("div",{className:"error-message",textContent:"Please enter link text"}),p=d("div",{className:"href-wrapper"}),E=d("div",{className:"search-icon",innerHTML:B({size:24})}),c=d("input",{type:"text",inputMode:"url",value:o.href,placeholder:"Enter URL",autocomplete:"new-password",spellcheck:!1}),g=d("div",{className:"error-message",textContent:"Please enter a valid URL"}),b=d("button",{type:"button",textContent:"Back",className:"back-button"}),u=d("button",{type:"submit",textContent:"Apply",className:"apply-button"}),L=(x,H)=>{x.classList.add("error"),H.classList.add("show")},T=(x,H)=>{x.classList.remove("error"),H.classList.remove("show")};h.addEventListener("input",()=>T(s,y)),c.addEventListener("input",()=>T(p,g)),b.addEventListener("click",()=>{e.onBack&&e.onBack()}),i.addEventListener("submit",x=>{x.preventDefault();let H=h.value.trim(),v=c.value.trim(),k=!1;H||(L(s,y),k=!0),C(v,{customValidator:r})||(L(p,g),k=!0),!k&&(t.chain().focus().extendMarkRange(e.markName??"hyperlink").editHyperlink({newURL:v,newText:H}).run(),w())}),s.append(f,h,y),p.append(E,c,g),l.append(s,p),m.append(b,u),i.append(l,m),w();let O=S({coordinates:{x:n.x,y:n.y,width:n.width,height:n.height,contextElement:a.dom},content:i,placement:"bottom",showArrow:!0,onShow:()=>h.focus()});setTimeout(()=>O.show(),ut)}function mt(e){let t=G(e);S({referenceElement:e.link,content:t,placement:"bottom",showArrow:!0}).show()}function G(e){let{link:t,editor:o}=e,n=e.attrs?.href??t.getAttribute("href")??"",r=d("div",{className:"hyperlink-preview-popover"}),a=d("button",{className:"remove",innerHTML:se()}),i=d("button",{className:"copy",innerHTML:ae()}),l=d("button",{className:"edit",innerHTML:le()}),m=d("a",{target:"_blank",rel:"noreferrer",href:n,innerText:n});return m.addEventListener("click",s=>{s.preventDefault(),R.test(n)||window.open(n,"_blank")}),a.addEventListener("click",()=>{w(),o.chain().focus().unsetHyperlink().run()}),l.addEventListener("click",()=>{W({...e,onBack:()=>mt(e)})}),i.addEventListener("click",()=>{ie(n,s=>{s?w():console.error("Failed to copy to clipboard")})}),r.append(m,i,l,a),r}import{registerCustomProtocol as Po}from"linkifyjs";var Ho=re;export{ae as Copy,R as DANGEROUS_SCHEME_RE,q as DEFAULT_OFFSET,re as Hyperlink,B as Link,se as LinkOff,le as Pencil,ce as Title,ie as copyToClipboard,S as createFloatingToolbar,d as createHTMLElement,pe as createHyperlinkPopover,Ho as default,At as destroyCurrentToolbar,W as editHyperlinkPopover,yt as getCategories,Mt as getCurrentToolbar,X as getSpecialUrlInfo,J as getUrlScheme,ht as getUrlsByCategory,w as hideCurrentToolbar,bt as isSpecialSchemeUrl,Ct as isToolbarVisible,P as normalizeHref,F as normalizeLinkifyHref,G as previewHyperlinkPopover,Po as registerCustomProtocol,Pt as updateCurrentToolbarPosition,C as validateURL};
22
+ //# sourceMappingURL=index.js.map