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