]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/Linkifier.ts
Merge pull request #566 from Tyriar/linkify_issues
[mirror_xterm.js.git] / src / Linkifier.ts
1 /**
2 * @license MIT
3 */
4
5 import { LinkMatcherOptions } from './Interfaces';
6 import { LinkMatcherHandler, LinkMatcherValidationCallback } from './Types';
7
8 type LinkMatcher = {
9 id: number,
10 regex: RegExp,
11 handler: LinkMatcherHandler,
12 matchIndex?: number,
13 validationCallback?: LinkMatcherValidationCallback;
14 };
15
16 const INVALID_LINK_CLASS = 'xterm-invalid-link';
17
18 const protocolClause = '(https?:\\/\\/)';
19 const domainCharacterSet = '[\\da-z\\.-]+';
20 const negatedDomainCharacterSet = '[^\\da-z\\.-]+';
21 const domainBodyClause = '(' + domainCharacterSet + ')';
22 const tldClause = '([a-z\\.]{2,6})';
23 const ipClause = '((\\d{1,3}\\.){3}\\d{1,3})';
24 const localHostClause = '(localhost)';
25 const portClause = '(:\\d{1,5})';
26 const hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + '|' + localHostClause + ')' + portClause + '?';
27 const pathClause = '(\\/[\\/\\w\\.\\-%]*)*';
28 const queryStringHashFragmentCharacterSet = '[0-9\\w\\[\\]\\(\\)\\/\\?\\!#@$%&\'*+,:;\\=\\.\\-]*';
29 const queryStringClause = '(\\?' + queryStringHashFragmentCharacterSet + ')?';
30 const hashFragmentClause = '(#' + queryStringHashFragmentCharacterSet + ')?';
31 const negatedPathCharacterSet = '[^\\/\\w\\.\\-%]+';
32 const bodyClause = hostClause + pathClause + queryStringClause + hashFragmentClause;
33 const start = '(?:^|' + negatedDomainCharacterSet + ')(';
34 const end = ')($|' + negatedPathCharacterSet + ')';
35 const strictUrlRegex = new RegExp(start + protocolClause + bodyClause + end);
36
37 /**
38 * The ID of the built in http(s) link matcher.
39 */
40 const HYPERTEXT_LINK_MATCHER_ID = 0;
41
42 /**
43 * The Linkifier applies links to rows shortly after they have been refreshed.
44 */
45 export class Linkifier {
46 /**
47 * The time to wait after a row is changed before it is linkified. This prevents
48 * the costly operation of searching every row multiple times, pntentially a
49 * huge aount of times.
50 */
51 protected static TIME_BEFORE_LINKIFY = 200;
52
53 private _document: Document;
54 private _rows: HTMLElement[];
55 private _rowTimeoutIds: number[];
56 private _linkMatchers: LinkMatcher[];
57 private _nextLinkMatcherId = HYPERTEXT_LINK_MATCHER_ID;
58
59 constructor(document: Document, rows: HTMLElement[]) {
60 this._document = document;
61 this._rows = rows;
62 this._rowTimeoutIds = [];
63 this._linkMatchers = [];
64 this.registerLinkMatcher(strictUrlRegex, null, 1);
65 }
66
67 /**
68 * Queues a row for linkification.
69 * @param {number} rowIndex The index of the row to linkify.
70 */
71 public linkifyRow(rowIndex: number): void {
72 const timeoutId = this._rowTimeoutIds[rowIndex];
73 if (timeoutId) {
74 clearTimeout(timeoutId);
75 }
76 this._rowTimeoutIds[rowIndex] = setTimeout(this._linkifyRow.bind(this, rowIndex), Linkifier.TIME_BEFORE_LINKIFY);
77 }
78
79 /**
80 * Attaches a handler for hypertext links, overriding default <a> behavior
81 * for standard http(s) links.
82 * @param {LinkHandler} handler The handler to use, this can be cleared with
83 * null.
84 */
85 public attachHypertextLinkHandler(handler: LinkMatcherHandler): void {
86 this._linkMatchers[HYPERTEXT_LINK_MATCHER_ID].handler = handler;
87 }
88
89 /**
90 * Registers a link matcher, allowing custom link patterns to be matched and
91 * handled.
92 * @param {RegExp} regex The regular expression to search for, specifically
93 * this searches the textContent of the rows. You will want to use \s to match
94 * a space ' ' character for example.
95 * @param {LinkHandler} handler The callback when the link is called.
96 * @param {LinkMatcherOptions} [options] Options for the link matcher.
97 * @return {number} The ID of the new matcher, this can be used to deregister.
98 */
99 public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options: LinkMatcherOptions = {}): number {
100 if (this._nextLinkMatcherId !== HYPERTEXT_LINK_MATCHER_ID && !handler) {
101 throw new Error('handler cannot be falsy');
102 }
103 const matcher: LinkMatcher = {
104 id: this._nextLinkMatcherId++,
105 regex,
106 handler,
107 matchIndex: options.matchIndex,
108 validationCallback: options.validationCallback
109 };
110 this._linkMatchers.push(matcher);
111 return matcher.id;
112 }
113
114 /**
115 * Deregisters a link matcher if it has been registered.
116 * @param {number} matcherId The link matcher's ID (returned after register)
117 * @return {boolean} Whether a link matcher was found and deregistered.
118 */
119 public deregisterLinkMatcher(matcherId: number): boolean {
120 // ID 0 is the hypertext link matcher which cannot be deregistered
121 for (let i = 1; i < this._linkMatchers.length; i++) {
122 if (this._linkMatchers[i].id === matcherId) {
123 this._linkMatchers.splice(i, 1);
124 return true;
125 }
126 }
127 return false;
128 }
129
130 /**
131 * Linkifies a row.
132 * @param {number} rowIndex The index of the row to linkify.
133 */
134 private _linkifyRow(rowIndex: number): void {
135 const row = this._rows[rowIndex];
136 if (!row) {
137 return;
138 }
139 const text = row.textContent;
140 // TODO: Onl execute handler if isValid
141 for (let i = 0; i < this._linkMatchers.length; i++) {
142 const matcher = this._linkMatchers[i];
143 const uri = this._findLinkMatch(text, matcher.regex, matcher.matchIndex);
144 if (uri) {
145 const linkElement = this._doLinkifyRow(rowIndex, uri, matcher.handler);
146 // Fire validation callback
147 if (linkElement && matcher.validationCallback) {
148 matcher.validationCallback(uri, isValid => {
149 if (!isValid) {
150 linkElement.classList.add(INVALID_LINK_CLASS);
151 }
152 });
153 }
154 // Only allow a single LinkMatcher to trigger on any given row.
155 return;
156 }
157 }
158 }
159
160 /**
161 * Linkifies a row given a specific handler.
162 * @param {number} rowIndex The index of the row to linkify.
163 * @param {string} uri The uri that has been found.
164 * @param {handler} handler The handler to trigger when the link is triggered.
165 * @return The link element if it was added, otherwise undefined.
166 */
167 private _doLinkifyRow(rowIndex: number, uri: string, handler?: LinkMatcherHandler): HTMLElement {
168 // Iterate over nodes as we want to consider text nodes
169 const nodes = this._rows[rowIndex].childNodes;
170 for (let i = 0; i < nodes.length; i++) {
171 const node = nodes[i];
172 const searchIndex = node.textContent.indexOf(uri);
173 if (searchIndex >= 0) {
174 const linkElement = this._createAnchorElement(uri, handler);
175 if (node.textContent.length === uri.length) {
176 // Matches entire string
177
178 if (node.nodeType === 3 /*Node.TEXT_NODE*/) {
179 this._replaceNode(node, linkElement);
180 } else {
181 const element = (<HTMLElement>node);
182 if (element.nodeName === 'A') {
183 // This row has already been linkified
184 return;
185 }
186 element.innerHTML = '';
187 element.appendChild(linkElement);
188 }
189 } else {
190 // Matches part of string
191 this._replaceNodeSubstringWithNode(node, linkElement, uri, searchIndex);
192 }
193 return linkElement;
194 }
195 }
196 }
197
198 /**
199 * Finds a link match in a piece of text.
200 * @param {string} text The text to search.
201 * @param {number} matchIndex The regex match index of the link.
202 * @return {string} The matching URI or null if not found.
203 */
204 private _findLinkMatch(text: string, regex: RegExp, matchIndex?: number): string {
205 const match = text.match(regex);
206 if (!match || match.length === 0) {
207 return null;
208 }
209 return match[typeof matchIndex !== 'number' ? 0 : matchIndex];
210 }
211
212 /**
213 * Creates a link anchor element.
214 * @param {string} uri The uri of the link.
215 * @return {HTMLAnchorElement} The link.
216 */
217 private _createAnchorElement(uri: string, handler: LinkMatcherHandler): HTMLAnchorElement {
218 const element = this._document.createElement('a');
219 element.textContent = uri;
220 if (handler) {
221 element.addEventListener('click', () => {
222 // Only execute the handler if the link is not flagged as invalid
223 if (!element.classList.contains(INVALID_LINK_CLASS)) {
224 handler(uri);
225 }
226 });
227 } else {
228 element.href = uri;
229 // Force link on another tab so work is not lost
230 element.target = '_blank';
231 }
232 return element;
233 }
234
235 /**
236 * Replace a node with 1 or more other nodes.
237 * @param {Node} oldNode The node to replace.
238 * @param {Node[]} newNodes The new nodes to insert in order.
239 */
240 private _replaceNode(oldNode: Node, ...newNodes: Node[]): void {
241 const parent = oldNode.parentNode;
242 for (let i = 0; i < newNodes.length; i++) {
243 parent.insertBefore(newNodes[i], oldNode);
244 }
245 parent.removeChild(oldNode);
246 }
247
248 /**
249 * Replace a substring within a node with a new node.
250 * @param {Node} targetNode The target node; either a text node or a <span>
251 * containing a single text node.
252 * @param {Node} newNode The new node to insert.
253 * @param {string} substring The substring to replace.
254 * @param {number} substringIndex The index of the substring within the string.
255 */
256 private _replaceNodeSubstringWithNode(targetNode: Node, newNode: Node, substring: string, substringIndex: number): void {
257 let node = targetNode;
258 if (node.nodeType !== 3/*Node.TEXT_NODE*/) {
259 node = node.childNodes[0];
260 }
261
262 // The targetNode will be either a text node or a <span>. The text node
263 // (targetNode or its only-child) needs to be replaced with newNode plus new
264 // text nodes potentially on either side.
265 if (node.childNodes.length === 0 && node.nodeType !== Node.TEXT_NODE) {
266 throw new Error('targetNode must be a text node or only contain a single text node');
267 }
268
269 const fullText = node.textContent;
270
271 if (substringIndex === 0) {
272 // Replace with <newNode><textnode>
273 const rightText = fullText.substring(substring.length);
274 const rightTextNode = this._document.createTextNode(rightText);
275 this._replaceNode(node, newNode, rightTextNode);
276 } else if (substringIndex === targetNode.textContent.length - substring.length) {
277 // Replace with <textnode><newNode>
278 const leftText = fullText.substring(0, substringIndex);
279 const leftTextNode = this._document.createTextNode(leftText);
280 this._replaceNode(node, leftTextNode, newNode);
281 } else {
282 // Replace with <textnode><newNode><textnode>
283 const leftText = fullText.substring(0, substringIndex);
284 const leftTextNode = this._document.createTextNode(leftText);
285 const rightText = fullText.substring(substringIndex + substring.length);
286 const rightTextNode = this._document.createTextNode(rightText);
287 this._replaceNode(node, leftTextNode, newNode, rightTextNode);
288 }
289 }
290 }