]> git.proxmox.com Git - mirror_xterm.js.git/blame - src/Linkifier.ts
Merge pull request #566 from Tyriar/linkify_issues
[mirror_xterm.js.git] / src / Linkifier.ts
CommitLineData
2207d356 1/**
55cb43d7 2 * @license MIT
2207d356 3 */
55cb43d7 4
6198556e 5import { LinkMatcherOptions } from './Interfaces';
4c99c032 6import { LinkMatcherHandler, LinkMatcherValidationCallback } from './Types';
55cb43d7 7
6198556e
DI
8type LinkMatcher = {
9 id: number,
10 regex: RegExp,
4c99c032 11 handler: LinkMatcherHandler,
6198556e
DI
12 matchIndex?: number,
13 validationCallback?: LinkMatcherValidationCallback;
14};
15
16const INVALID_LINK_CLASS = 'xterm-invalid-link';
2207d356 17
2207d356
DI
18const protocolClause = '(https?:\\/\\/)';
19const domainCharacterSet = '[\\da-z\\.-]+';
20const negatedDomainCharacterSet = '[^\\da-z\\.-]+';
21const domainBodyClause = '(' + domainCharacterSet + ')';
22const tldClause = '([a-z\\.]{2,6})';
23const ipClause = '((\\d{1,3}\\.){3}\\d{1,3})';
28d4ec77 24const localHostClause = '(localhost)';
2207d356 25const portClause = '(:\\d{1,5})';
28d4ec77 26const hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + '|' + localHostClause + ')' + portClause + '?';
7279ee0f 27const pathClause = '(\\/[\\/\\w\\.\\-%]*)*';
ccadf3fc 28const queryStringHashFragmentCharacterSet = '[0-9\\w\\[\\]\\(\\)\\/\\?\\!#@$%&\'*+,:;\\=\\.\\-]*';
9aae4396
DI
29const queryStringClause = '(\\?' + queryStringHashFragmentCharacterSet + ')?';
30const hashFragmentClause = '(#' + queryStringHashFragmentCharacterSet + ')?';
7279ee0f 31const negatedPathCharacterSet = '[^\\/\\w\\.\\-%]+';
9aae4396 32const bodyClause = hostClause + pathClause + queryStringClause + hashFragmentClause;
2207d356
DI
33const start = '(?:^|' + negatedDomainCharacterSet + ')(';
34const end = ')($|' + negatedPathCharacterSet + ')';
f7bc0fba 35const strictUrlRegex = new RegExp(start + protocolClause + bodyClause + end);
2207d356 36
55cb43d7
DI
37/**
38 * The ID of the built in http(s) link matcher.
39 */
7167b06b
DI
40const HYPERTEXT_LINK_MATCHER_ID = 0;
41
f7bc0fba
DI
42/**
43 * The Linkifier applies links to rows shortly after they have been refreshed.
44 */
2207d356 45export class Linkifier {
15d79143
DI
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
26ebc3d9 53 private _document: Document;
2207d356
DI
54 private _rows: HTMLElement[];
55 private _rowTimeoutIds: number[];
7167b06b 56 private _linkMatchers: LinkMatcher[];
5183332f 57 private _nextLinkMatcherId = HYPERTEXT_LINK_MATCHER_ID;
2207d356 58
26ebc3d9
DI
59 constructor(document: Document, rows: HTMLElement[]) {
60 this._document = document;
2207d356
DI
61 this._rows = rows;
62 this._rowTimeoutIds = [];
7167b06b 63 this._linkMatchers = [];
c8bb3216 64 this.registerLinkMatcher(strictUrlRegex, null, 1);
2207d356
DI
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 }
15d79143 76 this._rowTimeoutIds[rowIndex] = setTimeout(this._linkifyRow.bind(this, rowIndex), Linkifier.TIME_BEFORE_LINKIFY);
2207d356
DI
77 }
78
7167b06b 79 /**
3bf31aa4
DI
80 * Attaches a handler for hypertext links, overriding default <a> behavior
81 * for standard http(s) links.
7167b06b
DI
82 * @param {LinkHandler} handler The handler to use, this can be cleared with
83 * null.
84 */
4c99c032 85 public attachHypertextLinkHandler(handler: LinkMatcherHandler): void {
7167b06b
DI
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.
3b62aa44 92 * @param {RegExp} regex The regular expression to search for, specifically
1ee774d0
DI
93 * this searches the textContent of the rows. You will want to use \s to match
94 * a space ' ' character for example.
7167b06b 95 * @param {LinkHandler} handler The callback when the link is called.
6198556e 96 * @param {LinkMatcherOptions} [options] Options for the link matcher.
7167b06b
DI
97 * @return {number} The ID of the new matcher, this can be used to deregister.
98 */
4c99c032 99 public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options: LinkMatcherOptions = {}): number {
5183332f 100 if (this._nextLinkMatcherId !== HYPERTEXT_LINK_MATCHER_ID && !handler) {
7167b06b
DI
101 throw new Error('handler cannot be falsy');
102 }
103 const matcher: LinkMatcher = {
5183332f 104 id: this._nextLinkMatcherId++,
7167b06b 105 regex,
c8bb3216 106 handler,
6198556e
DI
107 matchIndex: options.matchIndex,
108 validationCallback: options.validationCallback
7167b06b
DI
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)
1c030f57 117 * @return {boolean} Whether a link matcher was found and deregistered.
7167b06b 118 */
1c030f57 119 public deregisterLinkMatcher(matcherId: number): boolean {
7167b06b
DI
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);
1c030f57 124 return true;
7167b06b
DI
125 }
126 }
1c030f57 127 return false;
2207d356
DI
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 {
c4f43184
DI
135 const row = this._rows[rowIndex];
136 if (!row) {
137 return;
138 }
139 const text = row.textContent;
6198556e 140 // TODO: Onl execute handler if isValid
e6fc80c1 141 for (let i = 0; i < this._linkMatchers.length; i++) {
7167b06b 142 const matcher = this._linkMatchers[i];
1ee774d0 143 const uri = this._findLinkMatch(text, matcher.regex, matcher.matchIndex);
7167b06b 144 if (uri) {
6198556e
DI
145 const linkElement = this._doLinkifyRow(rowIndex, uri, matcher.handler);
146 // Fire validation callback
dcffaf1c 147 if (linkElement && matcher.validationCallback) {
6198556e
DI
148 matcher.validationCallback(uri, isValid => {
149 if (!isValid) {
150 linkElement.classList.add(INVALID_LINK_CLASS);
151 }
152 });
153 }
7167b06b
DI
154 // Only allow a single LinkMatcher to trigger on any given row.
155 return;
156 }
a489037e 157 }
7167b06b 158 }
a489037e 159
7167b06b
DI
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.
6198556e 165 * @return The link element if it was added, otherwise undefined.
7167b06b 166 */
4c99c032 167 private _doLinkifyRow(rowIndex: number, uri: string, handler?: LinkMatcherHandler): HTMLElement {
a489037e
DI
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) {
7167b06b 174 const linkElement = this._createAnchorElement(uri, handler);
99a27021 175 if (node.textContent.length === uri.length) {
a489037e 176 // Matches entire string
26ebc3d9
DI
177
178 if (node.nodeType === 3 /*Node.TEXT_NODE*/) {
a489037e
DI
179 this._replaceNode(node, linkElement);
180 } else {
a489037e 181 const element = (<HTMLElement>node);
c8bb3216
DI
182 if (element.nodeName === 'A') {
183 // This row has already been linkified
184 return;
185 }
a489037e
DI
186 element.innerHTML = '';
187 element.appendChild(linkElement);
188 }
189 } else {
190 // Matches part of string
a489037e
DI
191 this._replaceNodeSubstringWithNode(node, linkElement, uri, searchIndex);
192 }
6198556e 193 return linkElement;
a489037e 194 }
2207d356
DI
195 }
196 }
197
198 /**
1ee774d0
DI
199 * Finds a link match in a piece of text.
200 * @param {string} text The text to search.
c8bb3216 201 * @param {number} matchIndex The regex match index of the link.
a489037e 202 * @return {string} The matching URI or null if not found.
2207d356 203 */
1ee774d0
DI
204 private _findLinkMatch(text: string, regex: RegExp, matchIndex?: number): string {
205 const match = text.match(regex);
2207d356
DI
206 if (!match || match.length === 0) {
207 return null;
208 }
c8bb3216 209 return match[typeof matchIndex !== 'number' ? 0 : matchIndex];
2207d356 210 }
a489037e
DI
211
212 /**
213 * Creates a link anchor element.
214 * @param {string} uri The uri of the link.
215 * @return {HTMLAnchorElement} The link.
216 */
4c99c032 217 private _createAnchorElement(uri: string, handler: LinkMatcherHandler): HTMLAnchorElement {
26ebc3d9 218 const element = this._document.createElement('a');
a489037e 219 element.textContent = uri;
7167b06b 220 if (handler) {
6198556e
DI
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 });
a489037e
DI
227 } else {
228 element.href = uri;
0f3ee21d
DI
229 // Force link on another tab so work is not lost
230 element.target = '_blank';
a489037e
DI
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.
0f3ee21d
DI
250 * @param {Node} targetNode The target node; either a text node or a <span>
251 * containing a single text node.
a489037e
DI
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;
26ebc3d9 258 if (node.nodeType !== 3/*Node.TEXT_NODE*/) {
a489037e
DI
259 node = node.childNodes[0];
260 }
0f3ee21d
DI
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.
a489037e
DI
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>
a489037e 273 const rightText = fullText.substring(substring.length);
26ebc3d9 274 const rightTextNode = this._document.createTextNode(rightText);
a489037e
DI
275 this._replaceNode(node, newNode, rightTextNode);
276 } else if (substringIndex === targetNode.textContent.length - substring.length) {
277 // Replace with <textnode><newNode>
a489037e 278 const leftText = fullText.substring(0, substringIndex);
26ebc3d9 279 const leftTextNode = this._document.createTextNode(leftText);
a489037e
DI
280 this._replaceNode(node, leftTextNode, newNode);
281 } else {
282 // Replace with <textnode><newNode><textnode>
a489037e 283 const leftText = fullText.substring(0, substringIndex);
26ebc3d9 284 const leftTextNode = this._document.createTextNode(leftText);
a489037e 285 const rightText = fullText.substring(substringIndex + substring.length);
26ebc3d9 286 const rightTextNode = this._document.createTextNode(rightText);
a489037e
DI
287 this._replaceNode(node, leftTextNode, newNode, rightTextNode);
288 }
289 }
2207d356 290}