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