Debian Codegraph @

closure-library/closure/goog/string/linkify.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Utility function for linkifying text.
17 * @author [email protected] (Michael Bolin)
18 */
19
20 goog.provide('goog.string.linkify');
21
22 goog.require('goog.html.SafeHtml');
23 goog.require('goog.string');
24
25
26 /**
27 * Takes a string of plain text and linkifies URLs and email addresses. For a
28 * URL (unless opt_attributes is specified), the target of the link will be
29 * _blank and it will have a rel=nofollow attribute applied to it so that links
30 * created by linkify will not be of interest to search engines.
31 * @param {string} text Plain text.
32 * @param {!Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes
33 * Attributes to add to all links created. Default are rel=nofollow and
34 * target=_blank. To clear those default attributes set rel='' and
35 * target=''.
36 * @param {boolean=} opt_preserveNewlines Whether to preserve newlines with
37 * &lt;br&gt;.
38 * @return {!goog.html.SafeHtml} Linkified HTML. Any text that is not part of a
39 * link will be HTML-escaped.
40 */
41 goog.string.linkify.linkifyPlainTextAsHtml = function(
42 text, opt_attributes, opt_preserveNewlines) {
43 // This shortcut makes linkifyPlainText ~10x faster if text doesn't contain
44 // URLs or email addresses and adds insignificant performance penalty if it
45 // does.
46 if (text.indexOf('@') == -1 && text.indexOf('://') == -1 &&
47 text.indexOf('www.') == -1 && text.indexOf('Www.') == -1 &&
48 text.indexOf('WWW.') == -1) {
49 return opt_preserveNewlines ?
50 goog.html.SafeHtml.htmlEscapePreservingNewlines(text) :
51 goog.html.SafeHtml.htmlEscape(text);
52 }
53
54 var attributesMap = {};
55 for (var key in opt_attributes) {
56 if (!opt_attributes[key]) {
57 // Our API allows '' to omit the attribute, SafeHtml requires null.
58 attributesMap[key] = null;
59 } else {
60 attributesMap[key] = opt_attributes[key];
61 }
62 }
63 // Set default options if they haven't been explicitly set.
64 if (!('rel' in attributesMap)) {
65 attributesMap['rel'] = 'nofollow';
66 }
67 if (!('target' in attributesMap)) {
68 attributesMap['target'] = '_blank';
69 }
70
71 var output = [];
72 // Return value is ignored.
73 text.replace(
74 goog.string.linkify.FIND_LINKS_RE_,
75 function(part, before, original, email, protocol) {
76 output.push(
77 opt_preserveNewlines ?
78 goog.html.SafeHtml.htmlEscapePreservingNewlines(before) :
79 before);
80 if (!original) {
81 return '';
82 }
83 var href = '';
84 /** @type {string} */
85 var linkText;
86 /** @type {string} */
87 var afterLink;
88 if (email) {
89 href = 'mailto:';
90 linkText = email;
91 afterLink = '';
92 } else {
93 // This is a full url link.
94 if (!protocol) {
95 href = 'http://';
96 }
97 var splitEndingPunctuation =
98 original.match(goog.string.linkify.ENDS_WITH_PUNCTUATION_RE_);
99 // An open paren in the link will often be matched with a close paren
100 // at the end, so skip cutting off ending punctuation if there's an
101 // open paren. For example:
102 // http://en.wikipedia.org/wiki/Titanic_(1997_film)
103 if (splitEndingPunctuation && !goog.string.contains(original, '(')) {
104 linkText = splitEndingPunctuation[1];
105 afterLink = splitEndingPunctuation[2];
106 } else {
107 linkText = original;
108 afterLink = '';
109 }
110 }
111 attributesMap['href'] = href + linkText;
112 output.push(goog.html.SafeHtml.create('a', attributesMap, linkText));
113 output.push(
114 opt_preserveNewlines ?
115 goog.html.SafeHtml.htmlEscapePreservingNewlines(afterLink) :
116 afterLink);
117 return '';
118 });
119 return goog.html.SafeHtml.concat(output);
120 };
121
122
123 /**
124 * Gets the first URI in text.
125 * @param {string} text Plain text.
126 * @return {string} The first URL, or an empty string if not found.
127 */
128 goog.string.linkify.findFirstUrl = function(text) {
129 var link = text.match(goog.string.linkify.URL_RE_);
130 return link != null ? link[0] : '';
131 };
132
133
134 /**
135 * Gets the first email address in text.
136 * @param {string} text Plain text.
137 * @return {string} The first email address, or an empty string if not found.
138 */
139 goog.string.linkify.findFirstEmail = function(text) {
140 var email = text.match(goog.string.linkify.EMAIL_RE_);
141 return email != null ? email[0] : '';
142 };
143
144
145 /**
146 * If a series of these characters is at the end of a url, it will be considered
147 * punctuation and not part of the url.
148 * @type {string}
149 * @const
150 * @private
151 */
152 goog.string.linkify.ENDING_PUNCTUATION_CHARS_ = ':;,\\.?}\\]\\)!';
153
154
155 /**
156 * @type {!RegExp}
157 * @const
158 * @private
159 */
160 goog.string.linkify.ENDS_WITH_PUNCTUATION_RE_ = new RegExp(
161 '^(.*?)([' + goog.string.linkify.ENDING_PUNCTUATION_CHARS_ + ']+)$');
162
163
164 /**
165 * Set of characters to be put into a regex character set ("[...]"), used to
166 * match against a url hostname and everything after it. It includes, in order,
167 * \w which represents [a-zA-Z0-9_], "#-;" which represents the characters
168 * "#$%&'()*+,-./0123456789:;" and the characters "!=?@[\]`{|}~".
169 * @type {string}
170 * @const
171 * @private
172 */
173 goog.string.linkify.ACCEPTABLE_URL_CHARS_ = '\\w#-;!=?@\\[\\\\\\]_`{|}~';
174
175
176 /**
177 * List of all protocols patterns recognized in urls (mailto is handled in email
178 * matching).
179 * @type {!Array<string>}
180 * @const
181 * @private
182 */
183 goog.string.linkify.RECOGNIZED_PROTOCOLS_ = ['https?', 'ftp'];
184
185
186 /**
187 * Regular expression pattern that matches the beginning of an url.
188 * Contains a catching group to capture the scheme.
189 * @type {string}
190 * @const
191 * @private
192 */
193 goog.string.linkify.PROTOCOL_START_ =
194 '(' + goog.string.linkify.RECOGNIZED_PROTOCOLS_.join('|') + ')://';
195
196
197 /**
198 * Regular expression pattern that matches the beginning of a typical
199 * http url without the http:// scheme.
200 * @type {string}
201 * @const
202 * @private
203 */
204 goog.string.linkify.WWW_START_ = 'www\\.';
205
206
207 /**
208 * Regular expression pattern that matches an url.
209 * @type {string}
210 * @const
211 * @private
212 */
213 goog.string.linkify.URL_RE_STRING_ = '(?:' +
214 goog.string.linkify.PROTOCOL_START_ + '|' + goog.string.linkify.WWW_START_ +
215 ')[' + goog.string.linkify.ACCEPTABLE_URL_CHARS_ + ']+';
216
217
218 /**
219 * Regular expression that matches an url. Case-insensitive.
220 * @type {!RegExp}
221 * @const
222 * @private
223 */
224 goog.string.linkify.URL_RE_ =
225 new RegExp(goog.string.linkify.URL_RE_STRING_, 'i');
226
227
228 /**
229 * Regular expression pattern that matches a top level domain.
230 * @type {string}
231 * @const
232 * @private
233 */
234 goog.string.linkify.TOP_LEVEL_DOMAIN_ = '(?:com|org|net|edu|gov' +
235 // from http://www.iana.org/gtld/gtld.htm
236 '|aero|biz|cat|coop|info|int|jobs|mobi|museum|name|pro|travel' +
237 '|arpa|asia|xxx' +
238 // a two letter country code
239 '|[a-z][a-z])\\b';
240
241
242 /**
243 * Regular expression pattern that matches an email.
244 * Contains a catching group to capture the email without the optional "mailto:"
245 * prefix.
246 * @type {string}
247 * @const
248 * @private
249 */
250 goog.string.linkify.EMAIL_RE_STRING_ =
251 '(?:mailto:)?([\\w.!#$%&\'*+-/=?^_`{|}~]+@[A-Za-z0-9.-]+\\.' +
252 goog.string.linkify.TOP_LEVEL_DOMAIN_ + ')';
253
254
255 /**
256 * Regular expression that matches an email. Case-insensitive.
257 * @type {!RegExp}
258 * @const
259 * @private
260 */
261 goog.string.linkify.EMAIL_RE_ =
262 new RegExp(goog.string.linkify.EMAIL_RE_STRING_, 'i');
263
264
265 /**
266 * Regular expression to match all the links (url or email) in a string.
267 * First match is text before first link, might be empty string.
268 * Second match is the original text that should be replaced by a link.
269 * Third match is the email address in the case of an email.
270 * Fourth match is the scheme of the url if specified.
271 * @type {!RegExp}
272 * @const
273 * @private
274 */
275 goog.string.linkify.FIND_LINKS_RE_ = new RegExp(
276 // Match everything including newlines.
277 '([\\S\\s]*?)(' +
278 // Match email after a word break.
279 '\\b' + goog.string.linkify.EMAIL_RE_STRING_ + '|' +
280 // Match url after a word break.
281 '\\b' + goog.string.linkify.URL_RE_STRING_ + '|$)',
282 'gi');