@tiptap/extension-link 2.0.0-beta.21 → 2.0.0-beta.210

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tiptap/extension-link",
3
3
  "description": "link extension for tiptap",
4
- "version": "2.0.0-beta.21",
4
+ "version": "2.0.0-beta.210",
5
5
  "homepage": "https://tiptap.dev",
6
6
  "keywords": [
7
7
  "tiptap",
@@ -12,25 +12,49 @@
12
12
  "type": "github",
13
13
  "url": "https://github.com/sponsors/ueberdosis"
14
14
  },
15
- "main": "dist/tiptap-extension-link.cjs.js",
16
- "umd": "dist/tiptap-extension-link.umd.js",
17
- "module": "dist/tiptap-extension-link.esm.js",
18
- "types": "dist/packages/extension-link/src/index.d.ts",
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "require": "./dist/index.cjs"
21
+ }
22
+ },
23
+ "main": "dist/index.cjs",
24
+ "module": "dist/index.js",
25
+ "types": "dist/index.d.ts",
19
26
  "files": [
20
27
  "src",
21
28
  "dist"
22
29
  ],
23
30
  "peerDependencies": {
24
- "@tiptap/core": "^2.0.0-beta.1"
31
+ "@tiptap/core": "^2.0.0-beta.209",
32
+ "@tiptap/pm": "^2.0.0-beta.209"
33
+ },
34
+ "devDependencies": {
35
+ "@tiptap/core": "^2.0.0-beta.210",
36
+ "@tiptap/pm": "^2.0.0-beta.210"
25
37
  },
26
38
  "dependencies": {
27
- "linkifyjs": "^3.0.1",
28
- "prosemirror-state": "^1.3.4"
39
+ "linkifyjs": "^3.0.5"
29
40
  },
30
41
  "repository": {
31
42
  "type": "git",
32
43
  "url": "https://github.com/ueberdosis/tiptap",
33
44
  "directory": "packages/extension-link"
34
45
  },
35
- "gitHead": "ed00dbbe56d7a31dbfcf02594c4ce5f54c7bc27a"
46
+ "scripts": {
47
+ "build": "tsup"
48
+ },
49
+ "tsup": {
50
+ "entry": [
51
+ "src/index.ts"
52
+ ],
53
+ "dts": true,
54
+ "splitting": true,
55
+ "format": [
56
+ "esm",
57
+ "cjs"
58
+ ]
59
+ }
36
60
  }
@@ -0,0 +1,142 @@
1
+ import {
2
+ combineTransactionSteps,
3
+ findChildrenInRange,
4
+ getChangedRanges,
5
+ getMarksBetween,
6
+ NodeWithPos,
7
+ } from '@tiptap/core'
8
+ import { MarkType } from '@tiptap/pm/model'
9
+ import { Plugin, PluginKey } from '@tiptap/pm/state'
10
+ import { find, test } from 'linkifyjs'
11
+
12
+ type AutolinkOptions = {
13
+ type: MarkType
14
+ validate?: (url: string) => boolean
15
+ }
16
+
17
+ export function autolink(options: AutolinkOptions): Plugin {
18
+ return new Plugin({
19
+ key: new PluginKey('autolink'),
20
+ appendTransaction: (transactions, oldState, newState) => {
21
+ const docChanges = transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc)
22
+ const preventAutolink = transactions.some(transaction => transaction.getMeta('preventAutolink'))
23
+
24
+ if (!docChanges || preventAutolink) {
25
+ return
26
+ }
27
+
28
+ const { tr } = newState
29
+ const transform = combineTransactionSteps(oldState.doc, [...transactions])
30
+ const { mapping } = transform
31
+ const changes = getChangedRanges(transform)
32
+
33
+ changes.forEach(({ oldRange, newRange }) => {
34
+ // at first we check if we have to remove links
35
+ getMarksBetween(oldRange.from, oldRange.to, oldState.doc)
36
+ .filter(item => item.mark.type === options.type)
37
+ .forEach(oldMark => {
38
+ const newFrom = mapping.map(oldMark.from)
39
+ const newTo = mapping.map(oldMark.to)
40
+ const newMarks = getMarksBetween(newFrom, newTo, newState.doc).filter(
41
+ item => item.mark.type === options.type,
42
+ )
43
+
44
+ if (!newMarks.length) {
45
+ return
46
+ }
47
+
48
+ const newMark = newMarks[0]
49
+ const oldLinkText = oldState.doc.textBetween(oldMark.from, oldMark.to, undefined, ' ')
50
+ const newLinkText = newState.doc.textBetween(newMark.from, newMark.to, undefined, ' ')
51
+ const wasLink = test(oldLinkText)
52
+ const isLink = test(newLinkText)
53
+
54
+ // remove only the link, if it was a link before too
55
+ // because we don’t want to remove links that were set manually
56
+ if (wasLink && !isLink) {
57
+ tr.removeMark(newMark.from, newMark.to, options.type)
58
+ }
59
+ })
60
+
61
+ // now let’s see if we can add new links
62
+ const nodesInChangedRanges = findChildrenInRange(
63
+ newState.doc,
64
+ newRange,
65
+ node => node.isTextblock,
66
+ )
67
+
68
+ let textBlock: NodeWithPos | undefined
69
+ let textBeforeWhitespace: string | undefined
70
+
71
+ if (nodesInChangedRanges.length > 1) {
72
+ // Grab the first node within the changed ranges (ex. the first of two paragraphs when hitting enter)
73
+ textBlock = nodesInChangedRanges[0]
74
+ textBeforeWhitespace = newState.doc.textBetween(
75
+ textBlock.pos,
76
+ textBlock.pos + textBlock.node.nodeSize,
77
+ undefined,
78
+ ' ',
79
+ )
80
+ } else if (
81
+ nodesInChangedRanges.length
82
+ // We want to make sure to include the block seperator argument to treat hard breaks like spaces
83
+ && newState.doc.textBetween(newRange.from, newRange.to, ' ', ' ').endsWith(' ')
84
+ ) {
85
+ textBlock = nodesInChangedRanges[0]
86
+ textBeforeWhitespace = newState.doc.textBetween(
87
+ textBlock.pos,
88
+ newRange.to,
89
+ undefined,
90
+ ' ',
91
+ )
92
+ }
93
+
94
+ if (textBlock && textBeforeWhitespace) {
95
+ const wordsBeforeWhitespace = textBeforeWhitespace.split(' ').filter(s => s !== '')
96
+
97
+ if (wordsBeforeWhitespace.length <= 0) {
98
+ return false
99
+ }
100
+
101
+ const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1]
102
+ const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace)
103
+
104
+ if (!lastWordBeforeSpace) {
105
+ return false
106
+ }
107
+
108
+ find(lastWordBeforeSpace)
109
+ .filter(link => link.isLink)
110
+ .filter(link => {
111
+ if (options.validate) {
112
+ return options.validate(link.value)
113
+ }
114
+ return true
115
+ })
116
+ // calculate link position
117
+ .map(link => ({
118
+ ...link,
119
+ from: lastWordAndBlockOffset + link.start + 1,
120
+ to: lastWordAndBlockOffset + link.end + 1,
121
+ }))
122
+ // add link mark
123
+ .forEach(link => {
124
+ tr.addMark(
125
+ link.from,
126
+ link.to,
127
+ options.type.create({
128
+ href: link.href,
129
+ }),
130
+ )
131
+ })
132
+ }
133
+ })
134
+
135
+ if (!tr.steps.length) {
136
+ return
137
+ }
138
+
139
+ return tr
140
+ },
141
+ })
142
+ }
@@ -0,0 +1,27 @@
1
+ import { getAttributes } from '@tiptap/core'
2
+ import { MarkType } from '@tiptap/pm/model'
3
+ import { Plugin, PluginKey } from '@tiptap/pm/state'
4
+
5
+ type ClickHandlerOptions = {
6
+ type: MarkType
7
+ }
8
+
9
+ export function clickHandler(options: ClickHandlerOptions): Plugin {
10
+ return new Plugin({
11
+ key: new PluginKey('handleClickLink'),
12
+ props: {
13
+ handleClick: (view, pos, event) => {
14
+ const attrs = getAttributes(view.state, options.type.name)
15
+ const link = (event.target as HTMLElement)?.closest('a')
16
+
17
+ if (link && attrs.href) {
18
+ window.open(attrs.href, attrs.target)
19
+
20
+ return true
21
+ }
22
+
23
+ return false
24
+ },
25
+ },
26
+ })
27
+ }
@@ -0,0 +1,44 @@
1
+ import { Editor } from '@tiptap/core'
2
+ import { MarkType } from '@tiptap/pm/model'
3
+ import { Plugin, PluginKey } from '@tiptap/pm/state'
4
+ import { find } from 'linkifyjs'
5
+
6
+ type PasteHandlerOptions = {
7
+ editor: Editor
8
+ type: MarkType
9
+ }
10
+
11
+ export function pasteHandler(options: PasteHandlerOptions): Plugin {
12
+ return new Plugin({
13
+ key: new PluginKey('handlePasteLink'),
14
+ props: {
15
+ handlePaste: (view, event, slice) => {
16
+ const { state } = view
17
+ const { selection } = state
18
+ const { empty } = selection
19
+
20
+ if (empty) {
21
+ return false
22
+ }
23
+
24
+ let textContent = ''
25
+
26
+ slice.content.forEach(node => {
27
+ textContent += node.textContent
28
+ })
29
+
30
+ const link = find(textContent).find(item => item.isLink && item.value === textContent)
31
+
32
+ if (!textContent || !link) {
33
+ return false
34
+ }
35
+
36
+ options.editor.commands.setMark(options.type, {
37
+ href: link.href,
38
+ })
39
+
40
+ return true
41
+ },
42
+ },
43
+ })
44
+ }
package/src/link.ts CHANGED
@@ -1,24 +1,38 @@
1
- import {
2
- Mark,
3
- markPasteRule,
4
- mergeAttributes,
5
- } from '@tiptap/core'
6
- import { Plugin, PluginKey } from 'prosemirror-state'
7
- import { find } from 'linkifyjs'
1
+ import { Mark, markPasteRule, mergeAttributes } from '@tiptap/core'
2
+ import { Plugin } from '@tiptap/pm/state'
3
+ import { find, registerCustomProtocol, reset } from 'linkifyjs'
4
+
5
+ import { autolink } from './helpers/autolink'
6
+ import { clickHandler } from './helpers/clickHandler'
7
+ import { pasteHandler } from './helpers/pasteHandler'
8
8
 
9
9
  export interface LinkOptions {
10
+ /**
11
+ * If enabled, it adds links as you type.
12
+ */
13
+ autolink: boolean
14
+ /**
15
+ * An array of custom protocols to be registered with linkifyjs.
16
+ */
17
+ protocols: Array<string>
10
18
  /**
11
19
  * If enabled, links will be opened on click.
12
20
  */
13
- openOnClick: boolean,
21
+ openOnClick: boolean
14
22
  /**
15
23
  * Adds a link to the current selection if the pasted content only contains an url.
16
24
  */
17
- linkOnPaste: boolean,
25
+ linkOnPaste: boolean
18
26
  /**
19
27
  * A list of HTML attributes to be rendered.
20
28
  */
21
- HTMLAttributes: Record<string, any>,
29
+ HTMLAttributes: Record<string, any>
30
+ /**
31
+ * A validation function that modifies link verification for the auto linker.
32
+ * @param url - The url to be validated.
33
+ * @returns - True if the url is valid, false otherwise.
34
+ */
35
+ validate?: (url: string) => boolean
22
36
  }
23
37
 
24
38
  declare module '@tiptap/core' {
@@ -27,15 +41,15 @@ declare module '@tiptap/core' {
27
41
  /**
28
42
  * Set a link mark
29
43
  */
30
- setLink: (attributes: { href: string, target?: string }) => ReturnType,
44
+ setLink: (attributes: { href: string; target?: string | null }) => ReturnType
31
45
  /**
32
46
  * Toggle a link mark
33
47
  */
34
- toggleLink: (attributes: { href: string, target?: string }) => ReturnType,
48
+ toggleLink: (attributes: { href: string; target?: string | null }) => ReturnType
35
49
  /**
36
50
  * Unset a link mark
37
51
  */
38
- unsetLink: () => ReturnType,
52
+ unsetLink: () => ReturnType
39
53
  }
40
54
  }
41
55
  }
@@ -45,15 +59,33 @@ export const Link = Mark.create<LinkOptions>({
45
59
 
46
60
  priority: 1000,
47
61
 
48
- inclusive: false,
62
+ keepOnSplit: false,
49
63
 
50
- defaultOptions: {
51
- openOnClick: true,
52
- linkOnPaste: true,
53
- HTMLAttributes: {
54
- target: '_blank',
55
- rel: 'noopener noreferrer nofollow',
56
- },
64
+ onCreate() {
65
+ this.options.protocols.forEach(registerCustomProtocol)
66
+ },
67
+
68
+ onDestroy() {
69
+ reset()
70
+ },
71
+
72
+ inclusive() {
73
+ return this.options.autolink
74
+ },
75
+
76
+ addOptions() {
77
+ return {
78
+ openOnClick: true,
79
+ linkOnPaste: true,
80
+ autolink: true,
81
+ protocols: [],
82
+ HTMLAttributes: {
83
+ target: '_blank',
84
+ rel: 'noopener noreferrer nofollow',
85
+ class: null,
86
+ },
87
+ validate: undefined,
88
+ }
57
89
  },
58
90
 
59
91
  addAttributes() {
@@ -64,13 +96,14 @@ export const Link = Mark.create<LinkOptions>({
64
96
  target: {
65
97
  default: this.options.HTMLAttributes.target,
66
98
  },
99
+ class: {
100
+ default: this.options.HTMLAttributes.class,
101
+ },
67
102
  }
68
103
  },
69
104
 
70
105
  parseHTML() {
71
- return [
72
- { tag: 'a[href]' },
73
- ]
106
+ return [{ tag: 'a[href]:not([href *= "javascript:" i])' }]
74
107
  },
75
108
 
76
109
  renderHTML({ HTMLAttributes }) {
@@ -79,15 +112,26 @@ export const Link = Mark.create<LinkOptions>({
79
112
 
80
113
  addCommands() {
81
114
  return {
82
- setLink: attributes => ({ commands }) => {
83
- return commands.setMark('link', attributes)
84
- },
85
- toggleLink: attributes => ({ commands }) => {
86
- return commands.toggleMark('link', attributes, { extendEmptyMarkRange: true })
87
- },
88
- unsetLink: () => ({ commands }) => {
89
- return commands.unsetMark('link', { extendEmptyMarkRange: true })
90
- },
115
+ setLink:
116
+ attributes => ({ chain }) => {
117
+ return chain().setMark(this.name, attributes).setMeta('preventAutolink', true).run()
118
+ },
119
+
120
+ toggleLink:
121
+ attributes => ({ chain }) => {
122
+ return chain()
123
+ .toggleMark(this.name, attributes, { extendEmptyMarkRange: true })
124
+ .setMeta('preventAutolink', true)
125
+ .run()
126
+ },
127
+
128
+ unsetLink:
129
+ () => ({ chain }) => {
130
+ return chain()
131
+ .unsetMark(this.name, { extendEmptyMarkRange: true })
132
+ .setMeta('preventAutolink', true)
133
+ .run()
134
+ },
91
135
  }
92
136
  },
93
137
 
@@ -95,6 +139,13 @@ export const Link = Mark.create<LinkOptions>({
95
139
  return [
96
140
  markPasteRule({
97
141
  find: text => find(text)
142
+ .filter(link => {
143
+ if (this.options.validate) {
144
+ return this.options.validate(link.value)
145
+ }
146
+
147
+ return true
148
+ })
98
149
  .filter(link => link.isLink)
99
150
  .map(link => ({
100
151
  text: link.value,
@@ -110,64 +161,30 @@ export const Link = Mark.create<LinkOptions>({
110
161
  },
111
162
 
112
163
  addProseMirrorPlugins() {
113
- const plugins = []
164
+ const plugins: Plugin[] = []
165
+
166
+ if (this.options.autolink) {
167
+ plugins.push(
168
+ autolink({
169
+ type: this.type,
170
+ validate: this.options.validate,
171
+ }),
172
+ )
173
+ }
114
174
 
115
175
  if (this.options.openOnClick) {
116
176
  plugins.push(
117
- new Plugin({
118
- key: new PluginKey('handleClickLink'),
119
- props: {
120
- handleClick: (view, pos, event) => {
121
- const attrs = this.editor.getAttributes('link')
122
- const link = (event.target as HTMLElement)?.closest('a')
123
-
124
- if (link && attrs.href) {
125
- window.open(attrs.href, attrs.target)
126
-
127
- return true
128
- }
129
-
130
- return false
131
- },
132
- },
177
+ clickHandler({
178
+ type: this.type,
133
179
  }),
134
180
  )
135
181
  }
136
182
 
137
183
  if (this.options.linkOnPaste) {
138
184
  plugins.push(
139
- new Plugin({
140
- key: new PluginKey('handlePasteLink'),
141
- props: {
142
- handlePaste: (view, event, slice) => {
143
- const { state } = view
144
- const { selection } = state
145
- const { empty } = selection
146
-
147
- if (empty) {
148
- return false
149
- }
150
-
151
- let textContent = ''
152
-
153
- slice.content.forEach(node => {
154
- textContent += node.textContent
155
- })
156
-
157
- const link = find(textContent)
158
- .find(item => item.isLink && item.value === textContent)
159
-
160
- if (!textContent || !link) {
161
- return false
162
- }
163
-
164
- this.editor.commands.setMark(this.type, {
165
- href: link.href,
166
- })
167
-
168
- return true
169
- },
170
- },
185
+ pasteHandler({
186
+ editor: this.editor,
187
+ type: this.type,
171
188
  }),
172
189
  )
173
190
  }
package/LICENSE.md DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2021, überdosis GbR
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,3 +0,0 @@
1
- import { Link } from './link';
2
- export * from './link';
3
- export default Link;
@@ -1,125 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var core = require('@tiptap/core');
6
- var prosemirrorState = require('prosemirror-state');
7
- var linkifyjs = require('linkifyjs');
8
-
9
- const Link = core.Mark.create({
10
- name: 'link',
11
- priority: 1000,
12
- inclusive: false,
13
- defaultOptions: {
14
- openOnClick: true,
15
- linkOnPaste: true,
16
- HTMLAttributes: {
17
- target: '_blank',
18
- rel: 'noopener noreferrer nofollow',
19
- },
20
- },
21
- addAttributes() {
22
- return {
23
- href: {
24
- default: null,
25
- },
26
- target: {
27
- default: this.options.HTMLAttributes.target,
28
- },
29
- };
30
- },
31
- parseHTML() {
32
- return [
33
- { tag: 'a[href]' },
34
- ];
35
- },
36
- renderHTML({ HTMLAttributes }) {
37
- return ['a', core.mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
38
- },
39
- addCommands() {
40
- return {
41
- setLink: attributes => ({ commands }) => {
42
- return commands.setMark('link', attributes);
43
- },
44
- toggleLink: attributes => ({ commands }) => {
45
- return commands.toggleMark('link', attributes, { extendEmptyMarkRange: true });
46
- },
47
- unsetLink: () => ({ commands }) => {
48
- return commands.unsetMark('link', { extendEmptyMarkRange: true });
49
- },
50
- };
51
- },
52
- addPasteRules() {
53
- return [
54
- core.markPasteRule({
55
- find: text => linkifyjs.find(text)
56
- .filter(link => link.isLink)
57
- .map(link => ({
58
- text: link.value,
59
- index: link.start,
60
- data: link,
61
- })),
62
- type: this.type,
63
- getAttributes: match => {
64
- var _a;
65
- return ({
66
- href: (_a = match.data) === null || _a === void 0 ? void 0 : _a.href,
67
- });
68
- },
69
- }),
70
- ];
71
- },
72
- addProseMirrorPlugins() {
73
- const plugins = [];
74
- if (this.options.openOnClick) {
75
- plugins.push(new prosemirrorState.Plugin({
76
- key: new prosemirrorState.PluginKey('handleClickLink'),
77
- props: {
78
- handleClick: (view, pos, event) => {
79
- var _a;
80
- const attrs = this.editor.getAttributes('link');
81
- const link = (_a = event.target) === null || _a === void 0 ? void 0 : _a.closest('a');
82
- if (link && attrs.href) {
83
- window.open(attrs.href, attrs.target);
84
- return true;
85
- }
86
- return false;
87
- },
88
- },
89
- }));
90
- }
91
- if (this.options.linkOnPaste) {
92
- plugins.push(new prosemirrorState.Plugin({
93
- key: new prosemirrorState.PluginKey('handlePasteLink'),
94
- props: {
95
- handlePaste: (view, event, slice) => {
96
- const { state } = view;
97
- const { selection } = state;
98
- const { empty } = selection;
99
- if (empty) {
100
- return false;
101
- }
102
- let textContent = '';
103
- slice.content.forEach(node => {
104
- textContent += node.textContent;
105
- });
106
- const link = linkifyjs.find(textContent)
107
- .find(item => item.isLink && item.value === textContent);
108
- if (!textContent || !link) {
109
- return false;
110
- }
111
- this.editor.commands.setMark(this.type, {
112
- href: link.href,
113
- });
114
- return true;
115
- },
116
- },
117
- }));
118
- }
119
- return plugins;
120
- },
121
- });
122
-
123
- exports.Link = Link;
124
- exports["default"] = Link;
125
- //# sourceMappingURL=tiptap-extension-link.cjs.js.map