@tiptap/extension-link 2.11.7 → 3.0.0-beta.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/index.js CHANGED
@@ -1,417 +1,388 @@
1
- import { combineTransactionSteps, getChangedRanges, findChildrenInRange, getMarksBetween, getAttributes, Mark, mergeAttributes, markPasteRule } from '@tiptap/core';
2
- import { tokenize, find, registerCustomProtocol, reset } from 'linkifyjs';
3
- import { Plugin, PluginKey } from '@tiptap/pm/state';
1
+ // src/link.ts
2
+ import { Mark, markPasteRule, mergeAttributes } from "@tiptap/core";
3
+ import { find as find2, registerCustomProtocol, reset } from "linkifyjs";
4
4
 
5
- /**
6
- * Check if the provided tokens form a valid link structure, which can either be a single link token
7
- * or a link token surrounded by parentheses or square brackets.
8
- *
9
- * This ensures that only complete and valid text is hyperlinked, preventing cases where a valid
10
- * top-level domain (TLD) is immediately followed by an invalid character, like a number. For
11
- * example, with the `find` method from Linkify, entering `example.com1` would result in
12
- * `example.com` being linked and the trailing `1` left as plain text. By using the `tokenize`
13
- * method, we can perform more comprehensive validation on the input text.
14
- */
5
+ // src/helpers/autolink.ts
6
+ import { combineTransactionSteps, findChildrenInRange, getChangedRanges, getMarksBetween } from "@tiptap/core";
7
+ import { Plugin, PluginKey } from "@tiptap/pm/state";
8
+ import { tokenize } from "linkifyjs";
15
9
  function isValidLinkStructure(tokens) {
16
- if (tokens.length === 1) {
17
- return tokens[0].isLink;
18
- }
19
- if (tokens.length === 3 && tokens[1].isLink) {
20
- return ['()', '[]'].includes(tokens[0].value + tokens[2].value);
21
- }
22
- return false;
10
+ if (tokens.length === 1) {
11
+ return tokens[0].isLink;
12
+ }
13
+ if (tokens.length === 3 && tokens[1].isLink) {
14
+ return ["()", "[]"].includes(tokens[0].value + tokens[2].value);
15
+ }
16
+ return false;
23
17
  }
24
- /**
25
- * This plugin allows you to automatically add links to your editor.
26
- * @param options The plugin options
27
- * @returns The plugin instance
28
- */
29
18
  function autolink(options) {
30
- return new Plugin({
31
- key: new PluginKey('autolink'),
32
- appendTransaction: (transactions, oldState, newState) => {
33
- /**
34
- * Does the transaction change the document?
35
- */
36
- const docChanges = transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc);
37
- /**
38
- * Prevent autolink if the transaction is not a document change or if the transaction has the meta `preventAutolink`.
39
- */
40
- const preventAutolink = transactions.some(transaction => transaction.getMeta('preventAutolink'));
41
- /**
42
- * Prevent autolink if the transaction is not a document change
43
- * or if the transaction has the meta `preventAutolink`.
44
- */
45
- if (!docChanges || preventAutolink) {
46
- return;
19
+ return new Plugin({
20
+ key: new PluginKey("autolink"),
21
+ appendTransaction: (transactions, oldState, newState) => {
22
+ const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
23
+ const preventAutolink = transactions.some((transaction) => transaction.getMeta("preventAutolink"));
24
+ if (!docChanges || preventAutolink) {
25
+ return;
26
+ }
27
+ const { tr } = newState;
28
+ const transform = combineTransactionSteps(oldState.doc, [...transactions]);
29
+ const changes = getChangedRanges(transform);
30
+ changes.forEach(({ newRange }) => {
31
+ const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, (node) => node.isTextblock);
32
+ let textBlock;
33
+ let textBeforeWhitespace;
34
+ if (nodesInChangedRanges.length > 1) {
35
+ textBlock = nodesInChangedRanges[0];
36
+ textBeforeWhitespace = newState.doc.textBetween(
37
+ textBlock.pos,
38
+ textBlock.pos + textBlock.node.nodeSize,
39
+ void 0,
40
+ " "
41
+ );
42
+ } else if (nodesInChangedRanges.length && // We want to make sure to include the block seperator argument to treat hard breaks like spaces.
43
+ newState.doc.textBetween(newRange.from, newRange.to, " ", " ").endsWith(" ")) {
44
+ textBlock = nodesInChangedRanges[0];
45
+ textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, void 0, " ");
46
+ }
47
+ if (textBlock && textBeforeWhitespace) {
48
+ const wordsBeforeWhitespace = textBeforeWhitespace.split(" ").filter((s) => s !== "");
49
+ if (wordsBeforeWhitespace.length <= 0) {
50
+ return false;
51
+ }
52
+ const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1];
53
+ const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace);
54
+ if (!lastWordBeforeSpace) {
55
+ return false;
56
+ }
57
+ const linksBeforeSpace = tokenize(lastWordBeforeSpace).map((t) => t.toObject(options.defaultProtocol));
58
+ if (!isValidLinkStructure(linksBeforeSpace)) {
59
+ return false;
60
+ }
61
+ linksBeforeSpace.filter((link) => link.isLink).map((link) => ({
62
+ ...link,
63
+ from: lastWordAndBlockOffset + link.start + 1,
64
+ to: lastWordAndBlockOffset + link.end + 1
65
+ })).filter((link) => {
66
+ if (!newState.schema.marks.code) {
67
+ return true;
47
68
  }
48
- const { tr } = newState;
49
- const transform = combineTransactionSteps(oldState.doc, [...transactions]);
50
- const changes = getChangedRanges(transform);
51
- changes.forEach(({ newRange }) => {
52
- // Now let’s see if we can add new links.
53
- const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, node => node.isTextblock);
54
- let textBlock;
55
- let textBeforeWhitespace;
56
- if (nodesInChangedRanges.length > 1) {
57
- // Grab the first node within the changed ranges (ex. the first of two paragraphs when hitting enter).
58
- textBlock = nodesInChangedRanges[0];
59
- textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, textBlock.pos + textBlock.node.nodeSize, undefined, ' ');
60
- }
61
- else if (nodesInChangedRanges.length
62
- // We want to make sure to include the block seperator argument to treat hard breaks like spaces.
63
- && newState.doc.textBetween(newRange.from, newRange.to, ' ', ' ').endsWith(' ')) {
64
- textBlock = nodesInChangedRanges[0];
65
- textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, undefined, ' ');
66
- }
67
- if (textBlock && textBeforeWhitespace) {
68
- const wordsBeforeWhitespace = textBeforeWhitespace.split(' ').filter(s => s !== '');
69
- if (wordsBeforeWhitespace.length <= 0) {
70
- return false;
71
- }
72
- const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1];
73
- const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace);
74
- if (!lastWordBeforeSpace) {
75
- return false;
76
- }
77
- const linksBeforeSpace = tokenize(lastWordBeforeSpace).map(t => t.toObject(options.defaultProtocol));
78
- if (!isValidLinkStructure(linksBeforeSpace)) {
79
- return false;
80
- }
81
- linksBeforeSpace
82
- .filter(link => link.isLink)
83
- // Calculate link position.
84
- .map(link => ({
85
- ...link,
86
- from: lastWordAndBlockOffset + link.start + 1,
87
- to: lastWordAndBlockOffset + link.end + 1,
88
- }))
89
- // ignore link inside code mark
90
- .filter(link => {
91
- if (!newState.schema.marks.code) {
92
- return true;
93
- }
94
- return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code);
95
- })
96
- // validate link
97
- .filter(link => options.validate(link.value))
98
- // check whether should autolink
99
- .filter(link => options.shouldAutoLink(link.value))
100
- // Add link mark.
101
- .forEach(link => {
102
- if (getMarksBetween(link.from, link.to, newState.doc).some(item => item.mark.type === options.type)) {
103
- return;
104
- }
105
- tr.addMark(link.from, link.to, options.type.create({
106
- href: link.href,
107
- }));
108
- });
109
- }
110
- });
111
- if (!tr.steps.length) {
112
- return;
69
+ return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code);
70
+ }).filter((link) => options.validate(link.value)).filter((link) => options.shouldAutoLink(link.value)).forEach((link) => {
71
+ if (getMarksBetween(link.from, link.to, newState.doc).some((item) => item.mark.type === options.type)) {
72
+ return;
113
73
  }
114
- return tr;
115
- },
116
- });
74
+ tr.addMark(
75
+ link.from,
76
+ link.to,
77
+ options.type.create({
78
+ href: link.href
79
+ })
80
+ );
81
+ });
82
+ }
83
+ });
84
+ if (!tr.steps.length) {
85
+ return;
86
+ }
87
+ return tr;
88
+ }
89
+ });
117
90
  }
118
91
 
92
+ // src/helpers/clickHandler.ts
93
+ import { getAttributes } from "@tiptap/core";
94
+ import { Plugin as Plugin2, PluginKey as PluginKey2 } from "@tiptap/pm/state";
119
95
  function clickHandler(options) {
120
- return new Plugin({
121
- key: new PluginKey('handleClickLink'),
122
- props: {
123
- handleClick: (view, pos, event) => {
124
- var _a, _b;
125
- if (event.button !== 0) {
126
- return false;
127
- }
128
- if (!view.editable) {
129
- return false;
130
- }
131
- let a = event.target;
132
- const els = [];
133
- while (a.nodeName !== 'DIV') {
134
- els.push(a);
135
- a = a.parentNode;
136
- }
137
- if (!els.find(value => value.nodeName === 'A')) {
138
- return false;
139
- }
140
- const attrs = getAttributes(view.state, options.type.name);
141
- const link = event.target;
142
- const href = (_a = link === null || link === void 0 ? void 0 : link.href) !== null && _a !== void 0 ? _a : attrs.href;
143
- const target = (_b = link === null || link === void 0 ? void 0 : link.target) !== null && _b !== void 0 ? _b : attrs.target;
144
- if (link && href) {
145
- window.open(href, target);
146
- return true;
147
- }
148
- return false;
149
- },
150
- },
151
- });
96
+ return new Plugin2({
97
+ key: new PluginKey2("handleClickLink"),
98
+ props: {
99
+ handleClick: (view, pos, event) => {
100
+ var _a, _b;
101
+ if (event.button !== 0) {
102
+ return false;
103
+ }
104
+ if (!view.editable) {
105
+ return false;
106
+ }
107
+ let link = null;
108
+ if (event.target instanceof HTMLAnchorElement) {
109
+ link = event.target;
110
+ } else {
111
+ let a = event.target;
112
+ const els = [];
113
+ while (a.nodeName !== "DIV") {
114
+ els.push(a);
115
+ a = a.parentNode;
116
+ }
117
+ link = els.find((value) => value.nodeName === "A");
118
+ }
119
+ if (!link) {
120
+ return false;
121
+ }
122
+ const attrs = getAttributes(view.state, options.type.name);
123
+ const href = (_a = link == null ? void 0 : link.href) != null ? _a : attrs.href;
124
+ const target = (_b = link == null ? void 0 : link.target) != null ? _b : attrs.target;
125
+ if (link && href) {
126
+ window.open(href, target);
127
+ return true;
128
+ }
129
+ return false;
130
+ }
131
+ }
132
+ });
152
133
  }
153
134
 
135
+ // src/helpers/pasteHandler.ts
136
+ import { Plugin as Plugin3, PluginKey as PluginKey3 } from "@tiptap/pm/state";
137
+ import { find } from "linkifyjs";
154
138
  function pasteHandler(options) {
155
- return new Plugin({
156
- key: new PluginKey('handlePasteLink'),
157
- props: {
158
- handlePaste: (view, event, slice) => {
159
- const { state } = view;
160
- const { selection } = state;
161
- const { empty } = selection;
162
- if (empty) {
163
- return false;
164
- }
165
- let textContent = '';
166
- slice.content.forEach(node => {
167
- textContent += node.textContent;
168
- });
169
- const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find(item => item.isLink && item.value === textContent);
170
- if (!textContent || !link) {
171
- return false;
172
- }
173
- return options.editor.commands.setMark(options.type, {
174
- href: link.href,
175
- });
176
- },
177
- },
178
- });
139
+ return new Plugin3({
140
+ key: new PluginKey3("handlePasteLink"),
141
+ props: {
142
+ handlePaste: (view, event, slice) => {
143
+ const { state } = view;
144
+ const { selection } = state;
145
+ const { empty } = selection;
146
+ if (empty) {
147
+ return false;
148
+ }
149
+ let textContent = "";
150
+ slice.content.forEach((node) => {
151
+ textContent += node.textContent;
152
+ });
153
+ const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find(
154
+ (item) => item.isLink && item.value === textContent
155
+ );
156
+ if (!textContent || !link) {
157
+ return false;
158
+ }
159
+ return options.editor.commands.setMark(options.type, {
160
+ href: link.href
161
+ });
162
+ }
163
+ }
164
+ });
179
165
  }
180
166
 
181
- const pasteRegex = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi;
182
- // From DOMPurify
183
- // https://github.com/cure53/DOMPurify/blob/main/src/regexp.js
184
- // eslint-disable-next-line no-control-regex
185
- const ATTR_WHITESPACE = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g;
167
+ // src/link.ts
168
+ var pasteRegex = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi;
169
+ var ATTR_WHITESPACE = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g;
186
170
  function isAllowedUri(uri, protocols) {
187
- const allowedProtocols = [
188
- 'http',
189
- 'https',
190
- 'ftp',
191
- 'ftps',
192
- 'mailto',
193
- 'tel',
194
- 'callto',
195
- 'sms',
196
- 'cid',
197
- 'xmpp',
198
- ];
199
- if (protocols) {
200
- protocols.forEach(protocol => {
201
- const nextProtocol = typeof protocol === 'string' ? protocol : protocol.scheme;
202
- if (nextProtocol) {
203
- allowedProtocols.push(nextProtocol);
204
- }
205
- });
206
- }
207
- return (!uri
208
- || uri
209
- .replace(ATTR_WHITESPACE, '')
210
- .match(new RegExp(
211
- // eslint-disable-next-line no-useless-escape
212
- `^(?:(?:${allowedProtocols.join('|')}):|[^a-z]|[a-z0-9+.\-]+(?:[^a-z+.\-:]|$))`, 'i')));
171
+ const allowedProtocols = ["http", "https", "ftp", "ftps", "mailto", "tel", "callto", "sms", "cid", "xmpp"];
172
+ if (protocols) {
173
+ protocols.forEach((protocol) => {
174
+ const nextProtocol = typeof protocol === "string" ? protocol : protocol.scheme;
175
+ if (nextProtocol) {
176
+ allowedProtocols.push(nextProtocol);
177
+ }
178
+ });
179
+ }
180
+ return !uri || uri.replace(ATTR_WHITESPACE, "").match(
181
+ new RegExp(
182
+ // eslint-disable-next-line no-useless-escape
183
+ `^(?:(?:${allowedProtocols.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,
184
+ "i"
185
+ )
186
+ );
213
187
  }
214
- /**
215
- * This extension allows you to create links.
216
- * @see https://www.tiptap.dev/api/marks/link
217
- */
218
- const Link = Mark.create({
219
- name: 'link',
220
- priority: 1000,
221
- keepOnSplit: false,
222
- exitable: true,
223
- onCreate() {
224
- if (this.options.validate && !this.options.shouldAutoLink) {
225
- // Copy the validate function to the shouldAutoLink option
226
- this.options.shouldAutoLink = this.options.validate;
227
- console.warn('The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.');
188
+ var Link = Mark.create({
189
+ name: "link",
190
+ priority: 1e3,
191
+ keepOnSplit: false,
192
+ exitable: true,
193
+ onCreate() {
194
+ if (this.options.validate && !this.options.shouldAutoLink) {
195
+ this.options.shouldAutoLink = this.options.validate;
196
+ console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.");
197
+ }
198
+ this.options.protocols.forEach((protocol) => {
199
+ if (typeof protocol === "string") {
200
+ registerCustomProtocol(protocol);
201
+ return;
202
+ }
203
+ registerCustomProtocol(protocol.scheme, protocol.optionalSlashes);
204
+ });
205
+ },
206
+ onDestroy() {
207
+ reset();
208
+ },
209
+ inclusive() {
210
+ return this.options.autolink;
211
+ },
212
+ addOptions() {
213
+ return {
214
+ openOnClick: true,
215
+ linkOnPaste: true,
216
+ autolink: true,
217
+ protocols: [],
218
+ defaultProtocol: "http",
219
+ HTMLAttributes: {
220
+ target: "_blank",
221
+ rel: "noopener noreferrer nofollow",
222
+ class: null
223
+ },
224
+ isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols),
225
+ validate: (url) => !!url,
226
+ shouldAutoLink: (url) => !!url
227
+ };
228
+ },
229
+ addAttributes() {
230
+ return {
231
+ href: {
232
+ default: null,
233
+ parseHTML(element) {
234
+ return element.getAttribute("href");
228
235
  }
229
- this.options.protocols.forEach(protocol => {
230
- if (typeof protocol === 'string') {
231
- registerCustomProtocol(protocol);
232
- return;
233
- }
234
- registerCustomProtocol(protocol.scheme, protocol.optionalSlashes);
235
- });
236
- },
237
- onDestroy() {
238
- reset();
239
- },
240
- inclusive() {
241
- return this.options.autolink;
242
- },
243
- addOptions() {
244
- return {
245
- openOnClick: true,
246
- linkOnPaste: true,
247
- autolink: true,
248
- protocols: [],
249
- defaultProtocol: 'http',
250
- HTMLAttributes: {
251
- target: '_blank',
252
- rel: 'noopener noreferrer nofollow',
253
- class: null,
254
- },
255
- isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols),
256
- validate: url => !!url,
257
- shouldAutoLink: url => !!url,
258
- };
259
- },
260
- addAttributes() {
261
- return {
262
- href: {
263
- default: null,
264
- parseHTML(element) {
265
- return element.getAttribute('href');
266
- },
267
- },
268
- target: {
269
- default: this.options.HTMLAttributes.target,
270
- },
271
- rel: {
272
- default: this.options.HTMLAttributes.rel,
273
- },
274
- class: {
275
- default: this.options.HTMLAttributes.class,
276
- },
277
- };
278
- },
279
- parseHTML() {
280
- return [
281
- {
282
- tag: 'a[href]',
283
- getAttrs: dom => {
284
- const href = dom.getAttribute('href');
285
- // prevent XSS attacks
286
- if (!href
287
- || !this.options.isAllowedUri(href, {
288
- defaultValidate: url => !!isAllowedUri(url, this.options.protocols),
289
- protocols: this.options.protocols,
290
- defaultProtocol: this.options.defaultProtocol,
291
- })) {
292
- return false;
293
- }
294
- return null;
295
- },
296
- },
297
- ];
298
- },
299
- renderHTML({ HTMLAttributes }) {
300
- // prevent XSS attacks
301
- if (!this.options.isAllowedUri(HTMLAttributes.href, {
302
- defaultValidate: href => !!isAllowedUri(href, this.options.protocols),
236
+ },
237
+ target: {
238
+ default: this.options.HTMLAttributes.target
239
+ },
240
+ rel: {
241
+ default: this.options.HTMLAttributes.rel
242
+ },
243
+ class: {
244
+ default: this.options.HTMLAttributes.class
245
+ }
246
+ };
247
+ },
248
+ parseHTML() {
249
+ return [
250
+ {
251
+ tag: "a[href]",
252
+ getAttrs: (dom) => {
253
+ const href = dom.getAttribute("href");
254
+ if (!href || !this.options.isAllowedUri(href, {
255
+ defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols),
303
256
  protocols: this.options.protocols,
304
- defaultProtocol: this.options.defaultProtocol,
305
- })) {
306
- // strip out the href
307
- return [
308
- 'a',
309
- mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: '' }),
310
- 0,
311
- ];
257
+ defaultProtocol: this.options.defaultProtocol
258
+ })) {
259
+ return false;
260
+ }
261
+ return null;
312
262
  }
313
- return ['a', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
314
- },
315
- addCommands() {
316
- return {
317
- setLink: attributes => ({ chain }) => {
318
- const { href } = attributes;
319
- if (!this.options.isAllowedUri(href, {
320
- defaultValidate: url => !!isAllowedUri(url, this.options.protocols),
321
- protocols: this.options.protocols,
322
- defaultProtocol: this.options.defaultProtocol,
323
- })) {
324
- return false;
325
- }
326
- return chain().setMark(this.name, attributes).setMeta('preventAutolink', true).run();
327
- },
328
- toggleLink: attributes => ({ chain }) => {
329
- const { href } = attributes;
330
- if (!this.options.isAllowedUri(href, {
331
- defaultValidate: url => !!isAllowedUri(url, this.options.protocols),
332
- protocols: this.options.protocols,
333
- defaultProtocol: this.options.defaultProtocol,
334
- })) {
335
- return false;
336
- }
337
- return chain()
338
- .toggleMark(this.name, attributes, { extendEmptyMarkRange: true })
339
- .setMeta('preventAutolink', true)
340
- .run();
341
- },
342
- unsetLink: () => ({ chain }) => {
343
- return chain()
344
- .unsetMark(this.name, { extendEmptyMarkRange: true })
345
- .setMeta('preventAutolink', true)
346
- .run();
347
- },
348
- };
349
- },
350
- addPasteRules() {
351
- return [
352
- markPasteRule({
353
- find: text => {
354
- const foundLinks = [];
355
- if (text) {
356
- const { protocols, defaultProtocol } = this.options;
357
- const links = find(text).filter(item => item.isLink
358
- && this.options.isAllowedUri(item.value, {
359
- defaultValidate: href => !!isAllowedUri(href, protocols),
360
- protocols,
361
- defaultProtocol,
362
- }));
363
- if (links.length) {
364
- links.forEach(link => foundLinks.push({
365
- text: link.value,
366
- data: {
367
- href: link.href,
368
- },
369
- index: link.start,
370
- }));
371
- }
372
- }
373
- return foundLinks;
374
- },
375
- type: this.type,
376
- getAttributes: match => {
377
- var _a;
378
- return {
379
- href: (_a = match.data) === null || _a === void 0 ? void 0 : _a.href,
380
- };
381
- },
382
- }),
383
- ];
384
- },
385
- addProseMirrorPlugins() {
386
- const plugins = [];
387
- const { protocols, defaultProtocol } = this.options;
388
- if (this.options.autolink) {
389
- plugins.push(autolink({
390
- type: this.type,
391
- defaultProtocol: this.options.defaultProtocol,
392
- validate: url => this.options.isAllowedUri(url, {
393
- defaultValidate: href => !!isAllowedUri(href, protocols),
394
- protocols,
395
- defaultProtocol,
396
- }),
397
- shouldAutoLink: this.options.shouldAutoLink,
398
- }));
263
+ }
264
+ ];
265
+ },
266
+ renderHTML({ HTMLAttributes }) {
267
+ if (!this.options.isAllowedUri(HTMLAttributes.href, {
268
+ defaultValidate: (href) => !!isAllowedUri(href, this.options.protocols),
269
+ protocols: this.options.protocols,
270
+ defaultProtocol: this.options.defaultProtocol
271
+ })) {
272
+ return ["a", mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: "" }), 0];
273
+ }
274
+ return ["a", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
275
+ },
276
+ addCommands() {
277
+ return {
278
+ setLink: (attributes) => ({ chain }) => {
279
+ const { href } = attributes;
280
+ if (!this.options.isAllowedUri(href, {
281
+ defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols),
282
+ protocols: this.options.protocols,
283
+ defaultProtocol: this.options.defaultProtocol
284
+ })) {
285
+ return false;
399
286
  }
400
- if (this.options.openOnClick === true) {
401
- plugins.push(clickHandler({
402
- type: this.type,
403
- }));
287
+ return chain().setMark(this.name, attributes).setMeta("preventAutolink", true).run();
288
+ },
289
+ toggleLink: (attributes) => ({ chain }) => {
290
+ const { href } = attributes;
291
+ if (!this.options.isAllowedUri(href, {
292
+ defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols),
293
+ protocols: this.options.protocols,
294
+ defaultProtocol: this.options.defaultProtocol
295
+ })) {
296
+ return false;
404
297
  }
405
- if (this.options.linkOnPaste) {
406
- plugins.push(pasteHandler({
407
- editor: this.editor,
408
- defaultProtocol: this.options.defaultProtocol,
409
- type: this.type,
410
- }));
298
+ return chain().toggleMark(this.name, attributes, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run();
299
+ },
300
+ unsetLink: () => ({ chain }) => {
301
+ return chain().unsetMark(this.name, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run();
302
+ }
303
+ };
304
+ },
305
+ addPasteRules() {
306
+ return [
307
+ markPasteRule({
308
+ find: (text) => {
309
+ const foundLinks = [];
310
+ if (text) {
311
+ const { protocols, defaultProtocol } = this.options;
312
+ const links = find2(text).filter(
313
+ (item) => item.isLink && this.options.isAllowedUri(item.value, {
314
+ defaultValidate: (href) => !!isAllowedUri(href, protocols),
315
+ protocols,
316
+ defaultProtocol
317
+ })
318
+ );
319
+ if (links.length) {
320
+ links.forEach(
321
+ (link) => foundLinks.push({
322
+ text: link.value,
323
+ data: {
324
+ href: link.href
325
+ },
326
+ index: link.start
327
+ })
328
+ );
329
+ }
330
+ }
331
+ return foundLinks;
332
+ },
333
+ type: this.type,
334
+ getAttributes: (match) => {
335
+ var _a;
336
+ return {
337
+ href: (_a = match.data) == null ? void 0 : _a.href
338
+ };
411
339
  }
412
- return plugins;
413
- },
340
+ })
341
+ ];
342
+ },
343
+ addProseMirrorPlugins() {
344
+ const plugins = [];
345
+ const { protocols, defaultProtocol } = this.options;
346
+ if (this.options.autolink) {
347
+ plugins.push(
348
+ autolink({
349
+ type: this.type,
350
+ defaultProtocol: this.options.defaultProtocol,
351
+ validate: (url) => this.options.isAllowedUri(url, {
352
+ defaultValidate: (href) => !!isAllowedUri(href, protocols),
353
+ protocols,
354
+ defaultProtocol
355
+ }),
356
+ shouldAutoLink: this.options.shouldAutoLink
357
+ })
358
+ );
359
+ }
360
+ if (this.options.openOnClick === true) {
361
+ plugins.push(
362
+ clickHandler({
363
+ type: this.type
364
+ })
365
+ );
366
+ }
367
+ if (this.options.linkOnPaste) {
368
+ plugins.push(
369
+ pasteHandler({
370
+ editor: this.editor,
371
+ defaultProtocol: this.options.defaultProtocol,
372
+ type: this.type
373
+ })
374
+ );
375
+ }
376
+ return plugins;
377
+ }
414
378
  });
415
379
 
416
- export { Link, Link as default, isAllowedUri, pasteRegex };
417
- //# sourceMappingURL=index.js.map
380
+ // src/index.ts
381
+ var index_default = Link;
382
+ export {
383
+ Link,
384
+ index_default as default,
385
+ isAllowedUri,
386
+ pasteRegex
387
+ };
388
+ //# sourceMappingURL=index.js.map