]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/Linkifier.ts
Remove logs
[mirror_xterm.js.git] / src / Linkifier.ts
1 /**
2 * The time to wait after a row is changed before it is linkified. This prevents
3 * the costly operation of searching every row multiple times, pntentially a
4 * huge aount of times.
5 */
6 const TIME_BEFORE_LINKIFY = 200;
7
8 const protocolClause = '(https?:\\/\\/)';
9 const domainCharacterSet = '[\\da-z\\.-]+';
10 const negatedDomainCharacterSet = '[^\\da-z\\.-]+';
11 const domainBodyClause = '(' + domainCharacterSet + ')';
12 const tldClause = '([a-z\\.]{2,6})';
13 const ipClause = '((\\d{1,3}\\.){3}\\d{1,3})';
14 const portClause = '(:\\d{1,5})';
15 const hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + ')' + portClause + '?';
16 const pathClause = '(\\/[\\/\\w\\.-]*)*';
17 const negatedPathCharacterSet = '[^\\/\\w\\.-]+';
18 const bodyClause = hostClause + pathClause;
19 const start = '(?:^|' + negatedDomainCharacterSet + ')(';
20 const end = ')($|' + negatedPathCharacterSet + ')';
21 const strictUrlRegex = new RegExp(start + protocolClause + bodyClause + end);
22
23 export type LinkHandler = (uri: string) => void;
24
25 /**
26 * The Linkifier applies links to rows shortly after they have been refreshed.
27 */
28 export class Linkifier {
29 private _rows: HTMLElement[];
30 private _rowTimeoutIds: number[];
31 private _hypertextLinkHandler: LinkHandler;
32
33 constructor(rows: HTMLElement[]) {
34 this._rows = rows;
35 this._rowTimeoutIds = [];
36 }
37
38 /**
39 * Queues a row for linkification.
40 * @param {number} rowIndex The index of the row to linkify.
41 */
42 public linkifyRow(rowIndex: number): void {
43 const timeoutId = this._rowTimeoutIds[rowIndex];
44 if (timeoutId) {
45 clearTimeout(timeoutId);
46 }
47 this._rowTimeoutIds[rowIndex] = setTimeout(this._linkifyRow.bind(this, rowIndex), TIME_BEFORE_LINKIFY);
48 }
49
50 // TODO: Support local links
51 public attachHypertextLinkHandler(handler: LinkHandler): void {
52 this._hypertextLinkHandler = handler;
53 }
54
55 /**
56 * Linkifies a row.
57 * @param {number} rowIndex The index of the row to linkify.
58 */
59 private _linkifyRow(rowIndex: number): void {
60 const rowHtml = this._rows[rowIndex].innerHTML;
61 const uri = this._findLinkMatch(rowHtml);
62 if (!uri) {
63 return;
64 }
65
66 // Iterate over nodes as we want to consider text nodes
67 const nodes = this._rows[rowIndex].childNodes;
68 for (let i = 0; i < nodes.length; i++) {
69 const node = nodes[i];
70 const searchIndex = node.textContent.indexOf(uri);
71 if (searchIndex >= 0) {
72 if (node.childNodes.length > 0) {
73 // This row has already been linkified
74 return;
75 }
76
77 const linkElement = this._createAnchorElement(uri);
78 // TODO: Check if childNodes check is needed
79 if (node.textContent.trim().length === uri.length) {
80 // Matches entire string
81 if (node.nodeType === Node.TEXT_NODE) {
82 this._replaceNode(node, linkElement);
83 } else {
84 const element = (<HTMLElement>node);
85 element.innerHTML = '';
86 element.appendChild(linkElement);
87 }
88 } else {
89 // Matches part of string
90 this._replaceNodeSubstringWithNode(node, linkElement, uri, searchIndex);
91 }
92 }
93 }
94 }
95
96 /**
97 * Finds a link match in a piece of HTML.
98 * @param {string} html The HTML to search.
99 * @return {string} The matching URI or null if not found.
100 */
101 private _findLinkMatch(html: string): string {
102 const match = html.match(strictUrlRegex);
103 if (!match || match.length === 0) {
104 return null;
105 }
106 return match[1];
107 }
108
109 /**
110 * Creates a link anchor element.
111 * @param {string} uri The uri of the link.
112 * @return {HTMLAnchorElement} The link.
113 */
114 private _createAnchorElement(uri: string): HTMLAnchorElement {
115 const element = document.createElement('a');
116 element.textContent = uri;
117 if (this._hypertextLinkHandler) {
118 element.addEventListener('click', () => this._hypertextLinkHandler(uri));
119 } else {
120 element.href = uri;
121 // Force link on another tab so work is not lost
122 element.target = '_blank';
123 }
124 return element;
125 }
126
127 /**
128 * Replace a node with 1 or more other nodes.
129 * @param {Node} oldNode The node to replace.
130 * @param {Node[]} newNodes The new nodes to insert in order.
131 */
132 private _replaceNode(oldNode: Node, ...newNodes: Node[]): void {
133 const parent = oldNode.parentNode;
134 for (let i = 0; i < newNodes.length; i++) {
135 parent.insertBefore(newNodes[i], oldNode);
136 }
137 parent.removeChild(oldNode);
138 }
139
140 /**
141 * Replace a substring within a node with a new node.
142 * @param {Node} targetNode The target node; either a text node or a <span>
143 * containing a single text node.
144 * @param {Node} newNode The new node to insert.
145 * @param {string} substring The substring to replace.
146 * @param {number} substringIndex The index of the substring within the string.
147 */
148 private _replaceNodeSubstringWithNode(targetNode: Node, newNode: Node, substring: string, substringIndex: number): void {
149 let node = targetNode;
150 if (node.nodeType !== Node.TEXT_NODE) {
151 node = node.childNodes[0];
152 }
153
154 // The targetNode will be either a text node or a <span>. The text node
155 // (targetNode or its only-child) needs to be replaced with newNode plus new
156 // text nodes potentially on either side.
157 if (node.childNodes.length === 0 && node.nodeType !== Node.TEXT_NODE) {
158 throw new Error('targetNode must be a text node or only contain a single text node');
159 }
160
161 const fullText = node.textContent;
162
163 if (substringIndex === 0) {
164 // Replace with <newNode><textnode>
165 const rightText = fullText.substring(substring.length);
166 const rightTextNode = document.createTextNode(rightText);
167 this._replaceNode(node, newNode, rightTextNode);
168 } else if (substringIndex === targetNode.textContent.length - substring.length) {
169 // Replace with <textnode><newNode>
170 const leftText = fullText.substring(0, substringIndex);
171 const leftTextNode = document.createTextNode(leftText);
172 this._replaceNode(node, leftTextNode, newNode);
173 } else {
174 // Replace with <textnode><newNode><textnode>
175 const leftText = fullText.substring(0, substringIndex);
176 const leftTextNode = document.createTextNode(leftText);
177 const rightText = fullText.substring(substringIndex + substring.length);
178 const rightTextNode = document.createTextNode(rightText);
179 this._replaceNode(node, leftTextNode, newNode, rightTextNode);
180 }
181 }
182 }