-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathautolink.ts
274 lines (224 loc) · 7.43 KB
/
autolink.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/**
* @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module link/autolink
*/
import { Plugin } from 'ckeditor5/src/core';
import type { DocumentSelectionChangeEvent, Element, Model, Range } from 'ckeditor5/src/engine';
import { Delete, TextWatcher, getLastTextLine, type TextWatcherMatchedDataEvent } from 'ckeditor5/src/typing';
import type { EnterCommand, ShiftEnterCommand } from 'ckeditor5/src/enter';
import { addLinkProtocolIfApplicable, linkHasProtocol } from './utils';
const MIN_LINK_LENGTH_WITH_SPACE_AT_END = 4; // Ie: "t.co " (length 5).
// This was a tweak from https://gist.github.com/dperini/729294.
const URL_REG_EXP = new RegExp(
// Group 1: Line start or after a space.
'(^|\\s)' +
// Group 2: Detected URL (or e-mail).
'(' +
// Protocol identifier or short syntax "//"
// a. Full form http://[email protected]:8080/foo/bar.html#baz?foo=bar
'(' +
'(?:(?:(?:https?|ftp):)?\\/\\/)' +
// BasicAuth using user:pass (optional)
'(?:\\S+(?::\\S*)?@)?' +
'(?:' +
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broadcast addresses
// (first & last IP address of each class)
'(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])' +
'(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}' +
'(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))' +
'|' +
'(' +
// Do not allow `www.foo` - see https://github.com/ckeditor/ckeditor5/issues/8050.
'((?!www\\.)|(www\\.))' +
// Host & domain names.
'(?![-_])(?:[-_a-z0-9\\u00a1-\\uffff]{1,63}\\.)+' +
// TLD identifier name.
'(?:[a-z\\u00a1-\\uffff]{2,63})' +
')' +
')' +
// port number (optional)
'(?::\\d{2,5})?' +
// resource path (optional)
'(?:[/?#]\\S*)?' +
')' +
'|' +
// b. Short form (either www.example.com or [email protected])
'(' +
'(www.|(\\S+@))' +
// Host & domain names.
'((?![-_])(?:[-_a-z0-9\\u00a1-\\uffff]{1,63}\\.))+' +
// TLD identifier name.
'(?:[a-z\\u00a1-\\uffff]{2,63})' +
')' +
')$', 'i' );
const URL_GROUP_IN_MATCH = 2;
/**
* The autolink plugin.
*/
export default class AutoLink extends Plugin {
/**
* @inheritDoc
*/
public static get requires() {
return [ Delete ] as const;
}
/**
* @inheritDoc
*/
public static get pluginName() {
return 'AutoLink' as const;
}
/**
* @inheritDoc
*/
public init(): void {
const editor = this.editor;
const selection = editor.model.document.selection;
selection.on<DocumentSelectionChangeEvent>( 'change:range', () => {
// Disable plugin when selection is inside a code block.
this.isEnabled = !selection.anchor!.parent.is( 'element', 'codeBlock' );
} );
this._enableTypingHandling();
}
/**
* @inheritDoc
*/
public afterInit(): void {
this._enableEnterHandling();
this._enableShiftEnterHandling();
}
/**
* Enables autolinking on typing.
*/
private _enableTypingHandling(): void {
const editor = this.editor;
const watcher = new TextWatcher( editor.model, text => {
// 1. Detect <kbd>Space</kbd> after a text with a potential link.
if ( !isSingleSpaceAtTheEnd( text ) ) {
return;
}
// 2. Check text before last typed <kbd>Space</kbd>.
const url = getUrlAtTextEnd( text.substr( 0, text.length - 1 ) );
if ( url ) {
return { url };
}
} );
watcher.on<TextWatcherMatchedDataEvent<{ url: string }>>( 'matched:data', ( evt, data ) => {
const { batch, range, url } = data;
if ( !batch.isTyping ) {
return;
}
const linkEnd = range.end.getShiftedBy( -1 ); // Executed after a space character.
const linkStart = linkEnd.getShiftedBy( -url.length );
const linkRange = editor.model.createRange( linkStart, linkEnd );
this._applyAutoLink( url, linkRange );
} );
watcher.bind( 'isEnabled' ).to( this );
}
/**
* Enables autolinking on the <kbd>Enter</kbd> key.
*/
private _enableEnterHandling(): void {
const editor = this.editor;
const model = editor.model;
const enterCommand: EnterCommand | undefined = editor.commands.get( 'enter' );
if ( !enterCommand ) {
return;
}
enterCommand.on( 'execute', () => {
const position = model.document.selection.getFirstPosition()!;
if ( !position.parent.previousSibling ) {
return;
}
const rangeToCheck = model.createRangeIn( position.parent.previousSibling as Element );
this._checkAndApplyAutoLinkOnRange( rangeToCheck );
} );
}
/**
* Enables autolinking on the <kbd>Shift</kbd>+<kbd>Enter</kbd> keyboard shortcut.
*/
private _enableShiftEnterHandling(): void {
const editor = this.editor;
const model = editor.model;
const shiftEnterCommand: ShiftEnterCommand | undefined = editor.commands.get( 'shiftEnter' );
if ( !shiftEnterCommand ) {
return;
}
shiftEnterCommand.on( 'execute', () => {
const position = model.document.selection.getFirstPosition()!;
const rangeToCheck = model.createRange(
model.createPositionAt( position.parent, 0 ),
position.getShiftedBy( -1 )
);
this._checkAndApplyAutoLinkOnRange( rangeToCheck );
} );
}
/**
* Checks if the passed range contains a linkable text.
*/
private _checkAndApplyAutoLinkOnRange( rangeToCheck: Range ): void {
const model = this.editor.model;
const { text, range } = getLastTextLine( rangeToCheck, model );
const url = getUrlAtTextEnd( text );
if ( url ) {
const linkRange = model.createRange(
range.end.getShiftedBy( -url.length ),
range.end
);
this._applyAutoLink( url, linkRange );
}
}
/**
* Applies a link on a given range if the link should be applied.
*
* @param url The URL to link.
* @param range The text range to apply the link attribute to.
*/
private _applyAutoLink( url: string, range: Range ): void {
const model = this.editor.model;
const defaultProtocol = this.editor.config.get( 'link.defaultProtocol' );
const fullUrl = addLinkProtocolIfApplicable( url, defaultProtocol );
if ( !this.isEnabled || !isLinkAllowedOnRange( range, model ) || !linkHasProtocol( fullUrl ) || linkIsAlreadySet( range ) ) {
return;
}
this._persistAutoLink( fullUrl, range );
}
/**
* Enqueues autolink changes in the model.
*
* @param url The URL to link.
* @param range The text range to apply the link attribute to.
*/
private _persistAutoLink( url: string, range: Range ): void {
const model = this.editor.model;
const deletePlugin = this.editor.plugins.get( 'Delete' );
// Enqueue change to make undo step.
model.enqueueChange( writer => {
writer.setAttribute( 'linkHref', url, range );
model.enqueueChange( () => {
deletePlugin.requestUndoOnBackspace();
} );
} );
}
}
// Check if text should be evaluated by the plugin in order to reduce number of RegExp checks on whole text.
function isSingleSpaceAtTheEnd( text: string ): boolean {
return text.length > MIN_LINK_LENGTH_WITH_SPACE_AT_END && text[ text.length - 1 ] === ' ' && text[ text.length - 2 ] !== ' ';
}
function getUrlAtTextEnd( text: string ): string | null {
const match = URL_REG_EXP.exec( text );
return match ? match[ URL_GROUP_IN_MATCH ] : null;
}
function isLinkAllowedOnRange( range: Range, model: Model ): boolean {
return model.schema.checkAttributeInSelection( model.createSelection( range ), 'linkHref' );
}
function linkIsAlreadySet( range: Range ): boolean {
const item = range.start.nodeAfter;
return !!item && item.hasAttribute( 'linkHref' );
}