5 import { LinkMatcherOptions } from './Interfaces';
6 import { LinkMatcher, LinkMatcherHandler, LinkMatcherValidationCallback } from './Types';
8 const INVALID_LINK_CLASS = 'xterm-invalid-link';
10 const protocolClause = '(https?:\\/\\/)';
11 const domainCharacterSet = '[\\da-z\\.-]+';
12 const negatedDomainCharacterSet = '[^\\da-z\\.-]+';
13 const domainBodyClause = '(' + domainCharacterSet + ')';
14 const tldClause = '([a-z\\.]{2,6})';
15 const ipClause = '((\\d{1,3}\\.){3}\\d{1,3})';
16 const localHostClause = '(localhost)';
17 const portClause = '(:\\d{1,5})';
18 const hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + '|' + localHostClause + ')' + portClause + '?';
19 const pathClause = '(\\/[\\/\\w\\.\\-%~]*)*';
20 const queryStringHashFragmentCharacterSet = '[0-9\\w\\[\\]\\(\\)\\/\\?\\!#@$%&\'*+,:;~\\=\\.\\-]*';
21 const queryStringClause = '(\\?' + queryStringHashFragmentCharacterSet + ')?';
22 const hashFragmentClause = '(#' + queryStringHashFragmentCharacterSet + ')?';
23 const negatedPathCharacterSet = '[^\\/\\w\\.\\-%]+';
24 const bodyClause = hostClause + pathClause + queryStringClause + hashFragmentClause;
25 const start = '(?:^|' + negatedDomainCharacterSet + ')(';
26 const end = ')($|' + negatedPathCharacterSet + ')';
27 const strictUrlRegex = new RegExp(start + protocolClause + bodyClause + end);
30 * The ID of the built in http(s) link matcher.
32 const HYPERTEXT_LINK_MATCHER_ID = 0;
35 * The Linkifier applies links to rows shortly after they have been refreshed.
37 export class Linkifier {
39 * The time to wait after a row is changed before it is linkified. This prevents
40 * the costly operation of searching every row multiple times, pntentially a
41 * huge aount of times.
43 protected static TIME_BEFORE_LINKIFY = 200;
45 protected _linkMatchers: LinkMatcher[];
47 private _document: Document;
48 private _rows: HTMLElement[];
49 private _rowTimeoutIds: number[];
50 private _nextLinkMatcherId = HYPERTEXT_LINK_MATCHER_ID;
52 constructor(document: Document, rows: HTMLElement[]) {
53 this._document = document;
55 this._rowTimeoutIds = [];
56 this._linkMatchers = [];
57 this.registerLinkMatcher(strictUrlRegex, null, { matchIndex: 1 });
61 * Queues a row for linkification.
62 * @param {number} rowIndex The index of the row to linkify.
64 public linkifyRow(rowIndex: number): void {
65 const timeoutId = this._rowTimeoutIds[rowIndex];
67 clearTimeout(timeoutId);
69 this._rowTimeoutIds[rowIndex] = setTimeout(this._linkifyRow.bind(this, rowIndex), Linkifier.TIME_BEFORE_LINKIFY);
73 * Attaches a handler for hypertext links, overriding default <a> behavior
74 * for standard http(s) links.
75 * @param {LinkHandler} handler The handler to use, this can be cleared with
78 public attachHypertextLinkHandler(handler: LinkMatcherHandler): void {
79 this._linkMatchers[HYPERTEXT_LINK_MATCHER_ID].handler = handler;
83 * Registers a link matcher, allowing custom link patterns to be matched and
85 * @param {RegExp} regex The regular expression to search for, specifically
86 * this searches the textContent of the rows. You will want to use \s to match
87 * a space ' ' character for example.
88 * @param {LinkHandler} handler The callback when the link is called.
89 * @param {LinkMatcherOptions} [options] Options for the link matcher.
90 * @return {number} The ID of the new matcher, this can be used to deregister.
92 public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options: LinkMatcherOptions = {}): number {
93 if (this._nextLinkMatcherId !== HYPERTEXT_LINK_MATCHER_ID && !handler) {
94 throw new Error('handler must be defined');
96 const matcher: LinkMatcher = {
97 id: this._nextLinkMatcherId++,
100 matchIndex: options.matchIndex,
101 validationCallback: options.validationCallback,
102 priority: options.priority || 0
104 this._addLinkMatcherToList(matcher);
109 * Inserts a link matcher to the list in the correct position based on the
110 * priority of each link matcher. New link matchers of equal priority are
111 * considered after older link matchers.
112 * @param matcher The link matcher to be added.
114 private _addLinkMatcherToList(matcher: LinkMatcher): void {
115 if (this._linkMatchers.length === 0) {
116 this._linkMatchers.push(matcher);
120 for (let i = this._linkMatchers.length - 1; i >= 0; i--) {
121 if (matcher.priority <= this._linkMatchers[i].priority) {
122 this._linkMatchers.splice(i + 1, 0, matcher);
127 this._linkMatchers.splice(0, 0, matcher);
131 * Deregisters a link matcher if it has been registered.
132 * @param {number} matcherId The link matcher's ID (returned after register)
133 * @return {boolean} Whether a link matcher was found and deregistered.
135 public deregisterLinkMatcher(matcherId: number): boolean {
136 // ID 0 is the hypertext link matcher which cannot be deregistered
137 for (let i = 1; i < this._linkMatchers.length; i++) {
138 if (this._linkMatchers[i].id === matcherId) {
139 this._linkMatchers.splice(i, 1);
148 * @param {number} rowIndex The index of the row to linkify.
150 private _linkifyRow(rowIndex: number): void {
151 const row = this._rows[rowIndex];
155 const text = row.textContent;
156 for (let i = 0; i < this._linkMatchers.length; i++) {
157 const matcher = this._linkMatchers[i];
158 const uri = this._findLinkMatch(text, matcher.regex, matcher.matchIndex);
160 const linkElement = this._doLinkifyRow(rowIndex, uri, matcher.handler, matcher.id === HYPERTEXT_LINK_MATCHER_ID);
161 // Fire validation callback
162 if (linkElement && matcher.validationCallback) {
163 matcher.validationCallback(uri, isValid => {
165 linkElement.classList.add(INVALID_LINK_CLASS);
169 // Only allow a single LinkMatcher to trigger on any given row.
176 * Linkifies a row given a specific handler.
177 * @param {number} rowIndex The index of the row to linkify.
178 * @param {string} uri The uri that has been found.
179 * @param {handler} handler The handler to trigger when the link is triggered.
180 * @return The link element if it was added, otherwise undefined.
182 private _doLinkifyRow(rowIndex: number, uri: string, handler: LinkMatcherHandler, isHttpLinkMatcher: boolean): HTMLElement {
183 // Iterate over nodes as we want to consider text nodes
184 const nodes = this._rows[rowIndex].childNodes;
185 for (let i = 0; i < nodes.length; i++) {
186 const node = nodes[i];
187 const searchIndex = node.textContent.indexOf(uri);
188 if (searchIndex >= 0) {
189 const linkElement = this._createAnchorElement(uri, handler, isHttpLinkMatcher);
190 if (node.textContent.length === uri.length) {
191 // Matches entire string
193 if (node.nodeType === 3 /*Node.TEXT_NODE*/) {
194 this._replaceNode(node, linkElement);
196 const element = (<HTMLElement>node);
197 if (element.nodeName === 'A') {
198 // This row has already been linkified
201 element.innerHTML = '';
202 element.appendChild(linkElement);
205 // Matches part of string
206 this._replaceNodeSubstringWithNode(node, linkElement, uri, searchIndex);
214 * Finds a link match in a piece of text.
215 * @param {string} text The text to search.
216 * @param {number} matchIndex The regex match index of the link.
217 * @return {string} The matching URI or null if not found.
219 private _findLinkMatch(text: string, regex: RegExp, matchIndex?: number): string {
220 const match = text.match(regex);
221 if (!match || match.length === 0) {
224 return match[typeof matchIndex !== 'number' ? 0 : matchIndex];
228 * Creates a link anchor element.
229 * @param {string} uri The uri of the link.
230 * @return {HTMLAnchorElement} The link.
232 private _createAnchorElement(uri: string, handler: LinkMatcherHandler, isHypertextLinkHandler: boolean): HTMLAnchorElement {
233 const element = this._document.createElement('a');
234 element.textContent = uri;
235 if (isHypertextLinkHandler) {
237 // Force link on another tab so work is not lost
238 element.target = '_blank';
239 element.addEventListener('click', (event: MouseEvent) => {
241 return handler(event, uri);
245 element.addEventListener('click', (event: MouseEvent) => {
246 // Don't execute the handler if the link is flagged as invalid
247 if (element.classList.contains(INVALID_LINK_CLASS)) {
250 return handler(event, uri);
257 * Replace a node with 1 or more other nodes.
258 * @param {Node} oldNode The node to replace.
259 * @param {Node[]} newNodes The new nodes to insert in order.
261 private _replaceNode(oldNode: Node, ...newNodes: Node[]): void {
262 const parent = oldNode.parentNode;
263 for (let i = 0; i < newNodes.length; i++) {
264 parent.insertBefore(newNodes[i], oldNode);
266 parent.removeChild(oldNode);
270 * Replace a substring within a node with a new node.
271 * @param {Node} targetNode The target node; either a text node or a <span>
272 * containing a single text node.
273 * @param {Node} newNode The new node to insert.
274 * @param {string} substring The substring to replace.
275 * @param {number} substringIndex The index of the substring within the string.
277 private _replaceNodeSubstringWithNode(targetNode: Node, newNode: Node, substring: string, substringIndex: number): void {
278 let node = targetNode;
279 if (node.nodeType !== 3/*Node.TEXT_NODE*/) {
280 node = node.childNodes[0];
283 // The targetNode will be either a text node or a <span>. The text node
284 // (targetNode or its only-child) needs to be replaced with newNode plus new
285 // text nodes potentially on either side.
286 if (node.childNodes.length === 0 && node.nodeType !== Node.TEXT_NODE) {
287 throw new Error('targetNode must be a text node or only contain a single text node');
290 const fullText = node.textContent;
292 if (substringIndex === 0) {
293 // Replace with <newNode><textnode>
294 const rightText = fullText.substring(substring.length);
295 const rightTextNode = this._document.createTextNode(rightText);
296 this._replaceNode(node, newNode, rightTextNode);
297 } else if (substringIndex === targetNode.textContent.length - substring.length) {
298 // Replace with <textnode><newNode>
299 const leftText = fullText.substring(0, substringIndex);
300 const leftTextNode = this._document.createTextNode(leftText);
301 this._replaceNode(node, leftTextNode, newNode);
303 // Replace with <textnode><newNode><textnode>
304 const leftText = fullText.substring(0, substringIndex);
305 const leftTextNode = this._document.createTextNode(leftText);
306 const rightText = fullText.substring(substringIndex + substring.length);
307 const rightTextNode = this._document.createTextNode(rightText);
308 this._replaceNode(node, leftTextNode, newNode, rightTextNode);