]> git.proxmox.com Git - mirror_xterm.js.git/blame - src/Linkifier.ts
Merge pull request #926 from ficristo/search-fix
[mirror_xterm.js.git] / src / Linkifier.ts
CommitLineData
2207d356 1/**
55cb43d7 2 * @license MIT
2207d356 3 */
55cb43d7 4
6198556e 5import { LinkMatcherOptions } from './Interfaces';
7ac4f1a9 6import { LinkMatcher, LinkMatcherHandler, LinkMatcherValidationCallback } from './Types';
6198556e
DI
7
8const INVALID_LINK_CLASS = 'xterm-invalid-link';
2207d356 9
2207d356
DI
10const protocolClause = '(https?:\\/\\/)';
11const domainCharacterSet = '[\\da-z\\.-]+';
12const negatedDomainCharacterSet = '[^\\da-z\\.-]+';
13const domainBodyClause = '(' + domainCharacterSet + ')';
14const tldClause = '([a-z\\.]{2,6})';
15const ipClause = '((\\d{1,3}\\.){3}\\d{1,3})';
28d4ec77 16const localHostClause = '(localhost)';
2207d356 17const portClause = '(:\\d{1,5})';
28d4ec77 18const hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + '|' + localHostClause + ')' + portClause + '?';
b68180b9
DI
19const pathClause = '(\\/[\\/\\w\\.\\-%~]*)*';
20const queryStringHashFragmentCharacterSet = '[0-9\\w\\[\\]\\(\\)\\/\\?\\!#@$%&\'*+,:;~\\=\\.\\-]*';
9aae4396
DI
21const queryStringClause = '(\\?' + queryStringHashFragmentCharacterSet + ')?';
22const hashFragmentClause = '(#' + queryStringHashFragmentCharacterSet + ')?';
7279ee0f 23const negatedPathCharacterSet = '[^\\/\\w\\.\\-%]+';
9aae4396 24const bodyClause = hostClause + pathClause + queryStringClause + hashFragmentClause;
2207d356
DI
25const start = '(?:^|' + negatedDomainCharacterSet + ')(';
26const end = ')($|' + negatedPathCharacterSet + ')';
f7bc0fba 27const strictUrlRegex = new RegExp(start + protocolClause + bodyClause + end);
2207d356 28
55cb43d7
DI
29/**
30 * The ID of the built in http(s) link matcher.
31 */
7167b06b
DI
32const HYPERTEXT_LINK_MATCHER_ID = 0;
33
f7bc0fba
DI
34/**
35 * The Linkifier applies links to rows shortly after they have been refreshed.
36 */
2207d356 37export class Linkifier {
15d79143
DI
38 /**
39 * The time to wait after a row is changed before it is linkified. This prevents
26ccf2a3
I
40 * the costly operation of searching every row multiple times, potentially a
41 * huge amount of times.
15d79143
DI
42 */
43 protected static TIME_BEFORE_LINKIFY = 200;
44
7ac4f1a9
DI
45 protected _linkMatchers: LinkMatcher[];
46
26ebc3d9 47 private _document: Document;
2207d356
DI
48 private _rows: HTMLElement[];
49 private _rowTimeoutIds: number[];
5183332f 50 private _nextLinkMatcherId = HYPERTEXT_LINK_MATCHER_ID;
2207d356 51
b0624cad 52 constructor() {
2207d356 53 this._rowTimeoutIds = [];
7167b06b 54 this._linkMatchers = [];
012051c1 55 this.registerLinkMatcher(strictUrlRegex, null, { matchIndex: 1 });
2207d356
DI
56 }
57
b0624cad
DI
58 /**
59 * Attaches the linkifier to the DOM, enabling linkification.
60 * @param document The document object.
61 * @param rows The array of rows to apply links to.
62 */
63 public attachToDom(document: Document, rows: HTMLElement[]) {
64 this._document = document;
65 this._rows = rows;
66 }
67
2207d356
DI
68 /**
69 * Queues a row for linkification.
70 * @param {number} rowIndex The index of the row to linkify.
71 */
72 public linkifyRow(rowIndex: number): void {
b0624cad
DI
73 // Don't attempt linkify if not yet attached to DOM
74 if (!this._document) {
75 return;
76 }
77
2207d356
DI
78 const timeoutId = this._rowTimeoutIds[rowIndex];
79 if (timeoutId) {
80 clearTimeout(timeoutId);
81 }
15d79143 82 this._rowTimeoutIds[rowIndex] = setTimeout(this._linkifyRow.bind(this, rowIndex), Linkifier.TIME_BEFORE_LINKIFY);
2207d356
DI
83 }
84
7167b06b 85 /**
3bf31aa4
DI
86 * Attaches a handler for hypertext links, overriding default <a> behavior
87 * for standard http(s) links.
7167b06b
DI
88 * @param {LinkHandler} handler The handler to use, this can be cleared with
89 * null.
90 */
11f62bab 91 public setHypertextLinkHandler(handler: LinkMatcherHandler): void {
7167b06b
DI
92 this._linkMatchers[HYPERTEXT_LINK_MATCHER_ID].handler = handler;
93 }
94
11f62bab
DI
95 /**
96 * Attaches a validation callback for hypertext links.
97 * @param {LinkMatcherValidationCallback} callback The callback to use, this
98 * can be cleared with null.
99 */
100 public setHypertextValidationCallback(callback: LinkMatcherValidationCallback): void {
101 this._linkMatchers[HYPERTEXT_LINK_MATCHER_ID].validationCallback = callback;
102 }
103
7167b06b
DI
104 /**
105 * Registers a link matcher, allowing custom link patterns to be matched and
106 * handled.
3b62aa44 107 * @param {RegExp} regex The regular expression to search for, specifically
1ee774d0
DI
108 * this searches the textContent of the rows. You will want to use \s to match
109 * a space ' ' character for example.
7167b06b 110 * @param {LinkHandler} handler The callback when the link is called.
6198556e 111 * @param {LinkMatcherOptions} [options] Options for the link matcher.
7167b06b
DI
112 * @return {number} The ID of the new matcher, this can be used to deregister.
113 */
4c99c032 114 public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options: LinkMatcherOptions = {}): number {
5183332f 115 if (this._nextLinkMatcherId !== HYPERTEXT_LINK_MATCHER_ID && !handler) {
aafb5333 116 throw new Error('handler must be defined');
7167b06b
DI
117 }
118 const matcher: LinkMatcher = {
5183332f 119 id: this._nextLinkMatcherId++,
7167b06b 120 regex,
c8bb3216 121 handler,
6198556e 122 matchIndex: options.matchIndex,
7ac4f1a9
DI
123 validationCallback: options.validationCallback,
124 priority: options.priority || 0
7167b06b 125 };
7ac4f1a9 126 this._addLinkMatcherToList(matcher);
7167b06b
DI
127 return matcher.id;
128 }
129
7ac4f1a9
DI
130 /**
131 * Inserts a link matcher to the list in the correct position based on the
132 * priority of each link matcher. New link matchers of equal priority are
133 * considered after older link matchers.
134 * @param matcher The link matcher to be added.
135 */
136 private _addLinkMatcherToList(matcher: LinkMatcher): void {
137 if (this._linkMatchers.length === 0) {
138 this._linkMatchers.push(matcher);
139 return;
140 }
141
142 for (let i = this._linkMatchers.length - 1; i >= 0; i--) {
78d5fc95 143 if (matcher.priority <= this._linkMatchers[i].priority) {
7ac4f1a9
DI
144 this._linkMatchers.splice(i + 1, 0, matcher);
145 return;
146 }
147 }
148
78d5fc95 149 this._linkMatchers.splice(0, 0, matcher);
7ac4f1a9
DI
150 }
151
7167b06b
DI
152 /**
153 * Deregisters a link matcher if it has been registered.
154 * @param {number} matcherId The link matcher's ID (returned after register)
1c030f57 155 * @return {boolean} Whether a link matcher was found and deregistered.
7167b06b 156 */
1c030f57 157 public deregisterLinkMatcher(matcherId: number): boolean {
7167b06b
DI
158 // ID 0 is the hypertext link matcher which cannot be deregistered
159 for (let i = 1; i < this._linkMatchers.length; i++) {
160 if (this._linkMatchers[i].id === matcherId) {
161 this._linkMatchers.splice(i, 1);
1c030f57 162 return true;
7167b06b
DI
163 }
164 }
1c030f57 165 return false;
2207d356
DI
166 }
167
168 /**
169 * Linkifies a row.
170 * @param {number} rowIndex The index of the row to linkify.
171 */
172 private _linkifyRow(rowIndex: number): void {
c4f43184
DI
173 const row = this._rows[rowIndex];
174 if (!row) {
175 return;
176 }
177 const text = row.textContent;
e6fc80c1 178 for (let i = 0; i < this._linkMatchers.length; i++) {
7167b06b 179 const matcher = this._linkMatchers[i];
08fd050c
DI
180 const linkElements = this._doLinkifyRow(row, matcher);
181 if (linkElements.length > 0) {
6198556e 182 // Fire validation callback
08fd050c
DI
183 if (matcher.validationCallback) {
184 for (let j = 0; j < linkElements.length; j++) {
584ec681
DI
185 const element = linkElements[j];
186 matcher.validationCallback(element.textContent, element, isValid => {
08fd050c 187 if (!isValid) {
584ec681 188 element.classList.add(INVALID_LINK_CLASS);
08fd050c
DI
189 }
190 });
191 }
6198556e 192 }
7167b06b
DI
193 // Only allow a single LinkMatcher to trigger on any given row.
194 return;
195 }
a489037e 196 }
7167b06b 197 }
a489037e 198
7167b06b
DI
199 /**
200 * Linkifies a row given a specific handler.
08fd050c
DI
201 * @param {HTMLElement} row The row to linkify.
202 * @param {LinkMatcher} matcher The link matcher for this line.
29ac6a15 203 * @return The link element(s) that were added.
7167b06b 204 */
08fd050c 205 private _doLinkifyRow(row: HTMLElement, matcher: LinkMatcher): HTMLElement[] {
a489037e 206 // Iterate over nodes as we want to consider text nodes
08fd050c
DI
207 let result = [];
208 const isHttpLinkMatcher = matcher.id === HYPERTEXT_LINK_MATCHER_ID;
209 const nodes = row.childNodes;
210
211 // Find the first match
212 let match = row.textContent.match(matcher.regex);
213 if (!match || match.length === 0) {
214 return result;
215 }
216 let uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex];
217 // Set the next searches start index
218 let rowStartIndex = match.index + uri.length;
219
a489037e
DI
220 for (let i = 0; i < nodes.length; i++) {
221 const node = nodes[i];
222 const searchIndex = node.textContent.indexOf(uri);
223 if (searchIndex >= 0) {
08fd050c 224 const linkElement = this._createAnchorElement(uri, matcher.handler, isHttpLinkMatcher);
99a27021 225 if (node.textContent.length === uri.length) {
a489037e 226 // Matches entire string
26ebc3d9 227 if (node.nodeType === 3 /*Node.TEXT_NODE*/) {
a489037e
DI
228 this._replaceNode(node, linkElement);
229 } else {
a489037e 230 const element = (<HTMLElement>node);
c8bb3216
DI
231 if (element.nodeName === 'A') {
232 // This row has already been linkified
5546baa9 233 return result;
c8bb3216 234 }
a489037e
DI
235 element.innerHTML = '';
236 element.appendChild(linkElement);
237 }
29ac6a15
DI
238 } else if (node.childNodes.length > 1) {
239 // Matches part of string in an element with multiple child nodes
240 for (let j = 0; j < node.childNodes.length; j++) {
241 const childNode = node.childNodes[j];
242 const childSearchIndex = childNode.textContent.indexOf(uri);
243 if (childSearchIndex !== -1) {
244 // Match found in currentNode
245 this._replaceNodeSubstringWithNode(childNode, linkElement, uri, childSearchIndex);
246 // Don't need to count nodesAdded by replacing the node as this
247 // is a child node, not a top-level node.
248 break;
249 }
250 }
a489037e 251 } else {
29ac6a15 252 // Matches part of string in a single text node
08fd050c
DI
253 const nodesAdded = this._replaceNodeSubstringWithNode(node, linkElement, uri, searchIndex);
254 // No need to consider the new nodes
5546baa9 255 i += nodesAdded;
a489037e 256 }
08fd050c 257 result.push(linkElement);
2207d356 258
08fd050c
DI
259 // Find the next match
260 match = row.textContent.substring(rowStartIndex).match(matcher.regex);
261 if (!match || match.length === 0) {
262 return result;
263 }
264 uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex];
265 rowStartIndex += match.index + uri.length;
266 }
2207d356 267 }
08fd050c 268 return result;
2207d356 269 }
a489037e
DI
270
271 /**
272 * Creates a link anchor element.
273 * @param {string} uri The uri of the link.
274 * @return {HTMLAnchorElement} The link.
275 */
1f518b0b 276 private _createAnchorElement(uri: string, handler: LinkMatcherHandler, isHypertextLinkHandler: boolean): HTMLAnchorElement {
26ebc3d9 277 const element = this._document.createElement('a');
a489037e 278 element.textContent = uri;
adde8ab2 279 element.draggable = false;
1f518b0b 280 if (isHypertextLinkHandler) {
a489037e 281 element.href = uri;
0f3ee21d
DI
282 // Force link on another tab so work is not lost
283 element.target = '_blank';
aafb5333
DI
284 element.addEventListener('click', (event: MouseEvent) => {
285 if (handler) {
286 return handler(event, uri);
c7b4c2be
DI
287 }
288 });
1f518b0b
DI
289 } else {
290 element.addEventListener('click', (event: MouseEvent) => {
291 // Don't execute the handler if the link is flagged as invalid
292 if (element.classList.contains(INVALID_LINK_CLASS)) {
293 return;
294 }
295 return handler(event, uri);
296 });
a489037e
DI
297 }
298 return element;
299 }
300
301 /**
302 * Replace a node with 1 or more other nodes.
303 * @param {Node} oldNode The node to replace.
304 * @param {Node[]} newNodes The new nodes to insert in order.
305 */
306 private _replaceNode(oldNode: Node, ...newNodes: Node[]): void {
307 const parent = oldNode.parentNode;
308 for (let i = 0; i < newNodes.length; i++) {
309 parent.insertBefore(newNodes[i], oldNode);
310 }
311 parent.removeChild(oldNode);
312 }
313
314 /**
315 * Replace a substring within a node with a new node.
0f3ee21d
DI
316 * @param {Node} targetNode The target node; either a text node or a <span>
317 * containing a single text node.
a489037e
DI
318 * @param {Node} newNode The new node to insert.
319 * @param {string} substring The substring to replace.
320 * @param {number} substringIndex The index of the substring within the string.
08fd050c 321 * @return The number of nodes to skip when searching for the next uri.
a489037e 322 */
08fd050c 323 private _replaceNodeSubstringWithNode(targetNode: Node, newNode: Node, substring: string, substringIndex: number): number {
29ac6a15
DI
324 // If the targetNode is a non-text node with a single child, make the child
325 // the new targetNode.
326 if (targetNode.childNodes.length === 1) {
327 targetNode = targetNode.childNodes[0];
a489037e 328 }
0f3ee21d
DI
329
330 // The targetNode will be either a text node or a <span>. The text node
331 // (targetNode or its only-child) needs to be replaced with newNode plus new
332 // text nodes potentially on either side.
29ac6a15 333 if (targetNode.nodeType !== 3/*Node.TEXT_NODE*/) {
a489037e
DI
334 throw new Error('targetNode must be a text node or only contain a single text node');
335 }
336
29ac6a15 337 const fullText = targetNode.textContent;
a489037e
DI
338
339 if (substringIndex === 0) {
340 // Replace with <newNode><textnode>
a489037e 341 const rightText = fullText.substring(substring.length);
26ebc3d9 342 const rightTextNode = this._document.createTextNode(rightText);
29ac6a15 343 this._replaceNode(targetNode, newNode, rightTextNode);
08fd050c
DI
344 return 0;
345 }
346
347 if (substringIndex === targetNode.textContent.length - substring.length) {
a489037e 348 // Replace with <textnode><newNode>
a489037e 349 const leftText = fullText.substring(0, substringIndex);
26ebc3d9 350 const leftTextNode = this._document.createTextNode(leftText);
29ac6a15 351 this._replaceNode(targetNode, leftTextNode, newNode);
8c2db8dd 352 return 0;
a489037e 353 }
08fd050c
DI
354
355 // Replace with <textnode><newNode><textnode>
356 const leftText = fullText.substring(0, substringIndex);
357 const leftTextNode = this._document.createTextNode(leftText);
358 const rightText = fullText.substring(substringIndex + substring.length);
359 const rightTextNode = this._document.createTextNode(rightText);
29ac6a15 360 this._replaceNode(targetNode, leftTextNode, newNode, rightTextNode);
08fd050c 361 return 1;
a489037e 362 }
2207d356 363}