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