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