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