Debian Codegraph @

dist/Autolinker.js

raw symbols SCIP
1 /*!
2 * Autolinker.js
3 * 1.8.3
4 *
5 * Copyright(c) 2018 Gregory Jacobs <[email protected]>
6 * MIT License
7 *
8 * https://github.com/gregjacobs/Autolinker.js
9 */
10 ;(function(root, factory) {
11 if (typeof define === 'function' && define.amd) {
12 define([], factory);
13 } else if (typeof exports === 'object') {
14 module.exports = factory();
15 } else {
16 root.Autolinker = factory();
17 }
18 }(this, function() {
19 /**
20 * @class Autolinker
21 * @extends Object
22 *
23 * Utility class used to process a given string of text, and wrap the matches in
24 * the appropriate anchor (&lt;a&gt;) tags to turn them into links.
25 *
26 * Any of the configuration options may be provided in an Object (map) provided
27 * to the Autolinker constructor, which will configure how the {@link #link link()}
28 * method will process the links.
29 *
30 * For example:
31 *
32 * var autolinker = new Autolinker( {
33 * newWindow : false,
34 * truncate : 30
35 * } );
36 *
37 * var html = autolinker.link( "Joe went to www.yahoo.com" );
38 * // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>'
39 *
40 *
41 * The {@link #static-link static link()} method may also be used to inline
42 * options into a single call, which may be more convenient for one-off uses.
43 * For example:
44 *
45 * var html = Autolinker.link( "Joe went to www.yahoo.com", {
46 * newWindow : false,
47 * truncate : 30
48 * } );
49 * // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>'
50 *
51 *
52 * ## Custom Replacements of Links
53 *
54 * If the configuration options do not provide enough flexibility, a {@link #replaceFn}
55 * may be provided to fully customize the output of Autolinker. This function is
56 * called once for each URL/Email/Phone#/Hashtag/Mention (Twitter, Instagram, Soundcloud)
57 * match that is encountered.
58 *
59 * For example:
60 *
61 * var input = "..."; // string with URLs, Email Addresses, Phone #s, Hashtags, and Mentions (Twitter, Instagram, Soundcloud)
62 *
63 * var linkedText = Autolinker.link( input, {
64 * replaceFn : function( match ) {
65 * console.log( "href = ", match.getAnchorHref() );
66 * console.log( "text = ", match.getAnchorText() );
67 *
68 * switch( match.getType() ) {
69 * case 'url' :
70 * console.log( "url: ", match.getUrl() );
71 *
72 * if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) {
73 * var tag = match.buildTag(); // returns an `Autolinker.HtmlTag` instance, which provides mutator methods for easy changes
74 * tag.setAttr( 'rel', 'nofollow' );
75 * tag.addClass( 'external-link' );
76 *
77 * return tag;
78 *
79 * } else {
80 * return true; // let Autolinker perform its normal anchor tag replacement
81 * }
82 *
83 * case 'email' :
84 * var email = match.getEmail();
85 * console.log( "email: ", email );
86 *
87 * if( email === "[email protected]" ) {
88 * return false; // don't auto-link this particular email address; leave as-is
89 * } else {
90 * return; // no return value will have Autolinker perform its normal anchor tag replacement (same as returning `true`)
91 * }
92 *
93 * case 'phone' :
94 * var phoneNumber = match.getPhoneNumber();
95 * console.log( phoneNumber );
96 *
97 * return '<a href="http://newplace.to.link.phone.numbers.to/">' + phoneNumber + '</a>';
98 *
99 * case 'hashtag' :
100 * var hashtag = match.getHashtag();
101 * console.log( hashtag );
102 *
103 * return '<a href="http://newplace.to.link.hashtag.handles.to/">' + hashtag + '</a>';
104 *
105 * case 'mention' :
106 * var mention = match.getMention();
107 * console.log( mention );
108 *
109 * return '<a href="http://newplace.to.link.mention.to/">' + mention + '</a>';
110 * }
111 * }
112 * } );
113 *
114 *
115 * The function may return the following values:
116 *
117 * - `true` (Boolean): Allow Autolinker to replace the match as it normally
118 * would.
119 * - `false` (Boolean): Do not replace the current match at all - leave as-is.
120 * - Any String: If a string is returned from the function, the string will be
121 * used directly as the replacement HTML for the match.
122 * - An {@link Autolinker.HtmlTag} instance, which can be used to build/modify
123 * an HTML tag before writing out its HTML text.
124 *
125 * @constructor
126 * @param {Object} [cfg] The configuration options for the Autolinker instance,
127 * specified in an Object (map).
128 */
129 var Autolinker = function( cfg ) {
130 cfg = cfg || {};
131
132 this.version = Autolinker.version;
133
134 this.urls = this.normalizeUrlsCfg( cfg.urls );
135 this.email = typeof cfg.email === 'boolean' ? cfg.email : true;
136 this.phone = typeof cfg.phone === 'boolean' ? cfg.phone : true;
137 this.hashtag = cfg.hashtag || false;
138 this.mention = cfg.mention || false;
139 this.newWindow = typeof cfg.newWindow === 'boolean' ? cfg.newWindow : true;
140 this.stripPrefix = this.normalizeStripPrefixCfg( cfg.stripPrefix );
141 this.stripTrailingSlash = typeof cfg.stripTrailingSlash === 'boolean' ? cfg.stripTrailingSlash : true;
142 this.decodePercentEncoding = typeof cfg.decodePercentEncoding === 'boolean' ? cfg.decodePercentEncoding : true;
143
144 // Validate the value of the `mention` cfg
145 var mention = this.mention;
146 if( mention !== false && mention !== 'twitter' && mention !== 'instagram' && mention !== 'soundcloud' ) {
147 throw new Error( "invalid `mention` cfg - see docs" );
148 }
149
150 // Validate the value of the `hashtag` cfg
151 var hashtag = this.hashtag;
152 if( hashtag !== false && hashtag !== 'twitter' && hashtag !== 'facebook' && hashtag !== 'instagram' ) {
153 throw new Error( "invalid `hashtag` cfg - see docs" );
154 }
155
156 this.truncate = this.normalizeTruncateCfg( cfg.truncate );
157 this.className = cfg.className || '';
158 this.replaceFn = cfg.replaceFn || null;
159 this.context = cfg.context || this;
160
161 this.htmlParser = null;
162 this.matchers = null;
163 this.tagBuilder = null;
164 };
165
166
167
168 /**
169 * Automatically links URLs, Email addresses, Phone Numbers, Twitter handles,
170 * Hashtags, and Mentions found in the given chunk of HTML. Does not link URLs
171 * found within HTML tags.
172 *
173 * For instance, if given the text: `You should go to http://www.yahoo.com`,
174 * then the result will be `You should go to &lt;a href="http://www.yahoo.com"&gt;http://www.yahoo.com&lt;/a&gt;`
175 *
176 * Example:
177 *
178 * var linkedText = Autolinker.link( "Go to google.com", { newWindow: false } );
179 * // Produces: "Go to <a href="http://google.com">google.com</a>"
180 *
181 * @static
182 * @param {String} textOrHtml The HTML or text to find matches within (depending
183 * on if the {@link #urls}, {@link #email}, {@link #phone}, {@link #mention},
184 * {@link #hashtag}, and {@link #mention} options are enabled).
185 * @param {Object} [options] Any of the configuration options for the Autolinker
186 * class, specified in an Object (map). See the class description for an
187 * example call.
188 * @return {String} The HTML text, with matches automatically linked.
189 */
190 Autolinker.link = function( textOrHtml, options ) {
191 var autolinker = new Autolinker( options );
192 return autolinker.link( textOrHtml );
193 };
194
195
196
197 /**
198 * Parses the input `textOrHtml` looking for URLs, email addresses, phone
199 * numbers, username handles, and hashtags (depending on the configuration
200 * of the Autolinker instance), and returns an array of {@link Autolinker.match.Match}
201 * objects describing those matches (without making any replacements).
202 *
203 * Note that if parsing multiple pieces of text, it is slightly more efficient
204 * to create an Autolinker instance, and use the instance-level {@link #parse}
205 * method.
206 *
207 * Example:
208 *
209 * var matches = Autolinker.parse( "Hello google.com, I am [email protected]", {
210 * urls: true,
211 * email: true
212 * } );
213 *
214 * console.log( matches.length ); // 2
215 * console.log( matches[ 0 ].getType() ); // 'url'
216 * console.log( matches[ 0 ].getUrl() ); // 'google.com'
217 * console.log( matches[ 1 ].getType() ); // 'email'
218 * console.log( matches[ 1 ].getEmail() ); // '[email protected]'
219 *
220 * @static
221 * @param {String} textOrHtml The HTML or text to find matches within
222 * (depending on if the {@link #urls}, {@link #email}, {@link #phone},
223 * {@link #hashtag}, and {@link #mention} options are enabled).
224 * @param {Object} [options] Any of the configuration options for the Autolinker
225 * class, specified in an Object (map). See the class description for an
226 * example call.
227 * @return {Autolinker.match.Match[]} The array of Matches found in the
228 * given input `textOrHtml`.
229 */
230 Autolinker.parse = function( textOrHtml, options ) {
231 var autolinker = new Autolinker( options );
232 return autolinker.parse( textOrHtml );
233 };
234
235
236 /**
237 * @static
238 * @property {String} version (readonly)
239 *
240 * The Autolinker version number in the form major.minor.patch
241 *
242 * Ex: 0.25.1
243 */
244 Autolinker.version = '1.8.3';
245
246
247 Autolinker.prototype = {
248 constructor : Autolinker, // fix constructor property
249
250 /**
251 * @cfg {Boolean/Object} [urls]
252 *
253 * `true` if URLs should be automatically linked, `false` if they should not
254 * be. Defaults to `true`.
255 *
256 * Examples:
257 *
258 * urls: true
259 *
260 * // or
261 *
262 * urls: {
263 * schemeMatches : true,
264 * wwwMatches : true,
265 * tldMatches : true
266 * }
267 *
268 * As shown above, this option also accepts an Object form with 3 properties
269 * to allow for more customization of what exactly gets linked. All default
270 * to `true`:
271 *
272 * @cfg {Boolean} [urls.schemeMatches] `true` to match URLs found prefixed
273 * with a scheme, i.e. `http://google.com`, or `other+scheme://google.com`,
274 * `false` to prevent these types of matches.
275 * @cfg {Boolean} [urls.wwwMatches] `true` to match urls found prefixed with
276 * `'www.'`, i.e. `www.google.com`. `false` to prevent these types of
277 * matches. Note that if the URL had a prefixed scheme, and
278 * `schemeMatches` is true, it will still be linked.
279 * @cfg {Boolean} [urls.tldMatches] `true` to match URLs with known top
280 * level domains (.com, .net, etc.) that are not prefixed with a scheme or
281 * `'www.'`. This option attempts to match anything that looks like a URL
282 * in the given text. Ex: `google.com`, `asdf.org/?page=1`, etc. `false`
283 * to prevent these types of matches.
284 */
285
286 /**
287 * @cfg {Boolean} [email=true]
288 *
289 * `true` if email addresses should be automatically linked, `false` if they
290 * should not be.
291 */
292
293 /**
294 * @cfg {Boolean} [phone=true]
295 *
296 * `true` if Phone numbers ("(555)555-5555") should be automatically linked,
297 * `false` if they should not be.
298 */
299
300 /**
301 * @cfg {Boolean/String} [hashtag=false]
302 *
303 * A string for the service name to have hashtags (ex: "#myHashtag")
304 * auto-linked to. The currently-supported values are:
305 *
306 * - 'twitter'
307 * - 'facebook'
308 * - 'instagram'
309 *
310 * Pass `false` to skip auto-linking of hashtags.
311 */
312
313 /**
314 * @cfg {String/Boolean} [mention=false]
315 *
316 * A string for the service name to have mentions (ex: "@myuser")
317 * auto-linked to. The currently supported values are:
318 *
319 * - 'twitter'
320 * - 'instagram'
321 * - 'soundcloud'
322 *
323 * Defaults to `false` to skip auto-linking of mentions.
324 */
325
326 /**
327 * @cfg {Boolean} [newWindow=true]
328 *
329 * `true` if the links should open in a new window, `false` otherwise.
330 */
331
332 /**
333 * @cfg {Boolean/Object} [stripPrefix]
334 *
335 * `true` if 'http://' (or 'https://') and/or the 'www.' should be stripped
336 * from the beginning of URL links' text, `false` otherwise. Defaults to
337 * `true`.
338 *
339 * Examples:
340 *
341 * stripPrefix: true
342 *
343 * // or
344 *
345 * stripPrefix: {
346 * scheme : true,
347 * www : true
348 * }
349 *
350 * As shown above, this option also accepts an Object form with 2 properties
351 * to allow for more customization of what exactly is prevented from being
352 * displayed. Both default to `true`:
353 *
354 * @cfg {Boolean} [stripPrefix.scheme] `true` to prevent the scheme part of
355 * a URL match from being displayed to the user. Example:
356 * `'http://google.com'` will be displayed as `'google.com'`. `false` to
357 * not strip the scheme. NOTE: Only an `'http://'` or `'https://'` scheme
358 * will be removed, so as not to remove a potentially dangerous scheme
359 * (such as `'file://'` or `'javascript:'`)
360 * @cfg {Boolean} [stripPrefix.www] www (Boolean): `true` to prevent the
361 * `'www.'` part of a URL match from being displayed to the user. Ex:
362 * `'www.google.com'` will be displayed as `'google.com'`. `false` to not
363 * strip the `'www'`.
364 */
365
366 /**
367 * @cfg {Boolean} [stripTrailingSlash=true]
368 *
369 * `true` to remove the trailing slash from URL matches, `false` to keep
370 * the trailing slash.
371 *
372 * Example when `true`: `http://google.com/` will be displayed as
373 * `http://google.com`.
374 */
375
376 /**
377 * @cfg {Boolean} [decodePercentEncoding=true]
378 *
379 * `true` to decode percent-encoded characters in URL matches, `false` to keep
380 * the percent-encoded characters.
381 *
382 * Example when `true`: `https://en.wikipedia.org/wiki/San_Jos%C3%A9` will
383 * be displayed as `https://en.wikipedia.org/wiki/San_José`.
384 */
385
386 /**
387 * @cfg {Number/Object} [truncate=0]
388 *
389 * ## Number Form
390 *
391 * A number for how many characters matched text should be truncated to
392 * inside the text of a link. If the matched text is over this number of
393 * characters, it will be truncated to this length by adding a two period
394 * ellipsis ('..') to the end of the string.
395 *
396 * For example: A url like 'http://www.yahoo.com/some/long/path/to/a/file'
397 * truncated to 25 characters might look something like this:
398 * 'yahoo.com/some/long/pat..'
399 *
400 * Example Usage:
401 *
402 * truncate: 25
403 *
404 *
405 * Defaults to `0` for "no truncation."
406 *
407 *
408 * ## Object Form
409 *
410 * An Object may also be provided with two properties: `length` (Number) and
411 * `location` (String). `location` may be one of the following: 'end'
412 * (default), 'middle', or 'smart'.
413 *
414 * Example Usage:
415 *
416 * truncate: { length: 25, location: 'middle' }
417 *
418 * @cfg {Number} [truncate.length=0] How many characters to allow before
419 * truncation will occur. Defaults to `0` for "no truncation."
420 * @cfg {"end"/"middle"/"smart"} [truncate.location="end"]
421 *
422 * - 'end' (default): will truncate up to the number of characters, and then
423 * add an ellipsis at the end. Ex: 'yahoo.com/some/long/pat..'
424 * - 'middle': will truncate and add the ellipsis in the middle. Ex:
425 * 'yahoo.com/s..th/to/a/file'
426 * - 'smart': for URLs where the algorithm attempts to strip out unnecessary
427 * parts first (such as the 'www.', then URL scheme, hash, etc.),
428 * attempting to make the URL human-readable before looking for a good
429 * point to insert the ellipsis if it is still too long. Ex:
430 * 'yahoo.com/some..to/a/file'. For more details, see
431 * {@link Autolinker.truncate.TruncateSmart}.
432 */
433
434 /**
435 * @cfg {String} className
436 *
437 * A CSS class name to add to the generated links. This class will be added
438 * to all links, as well as this class plus match suffixes for styling
439 * url/email/phone/hashtag/mention links differently.
440 *
441 * For example, if this config is provided as "myLink", then:
442 *
443 * - URL links will have the CSS classes: "myLink myLink-url"
444 * - Email links will have the CSS classes: "myLink myLink-email", and
445 * - Phone links will have the CSS classes: "myLink myLink-phone"
446 * - Hashtag links will have the CSS classes: "myLink myLink-hashtag"
447 * - Mention links will have the CSS classes: "myLink myLink-mention myLink-[type]"
448 * where [type] is either "instagram", "twitter" or "soundcloud"
449 */
450
451 /**
452 * @cfg {Function} replaceFn
453 *
454 * A function to individually process each match found in the input string.
455 *
456 * See the class's description for usage.
457 *
458 * The `replaceFn` can be called with a different context object (`this`
459 * reference) using the {@link #context} cfg.
460 *
461 * This function is called with the following parameter:
462 *
463 * @cfg {Autolinker.match.Match} replaceFn.match The Match instance which
464 * can be used to retrieve information about the match that the `replaceFn`
465 * is currently processing. See {@link Autolinker.match.Match} subclasses
466 * for details.
467 */
468
469 /**
470 * @cfg {Object} context
471 *
472 * The context object (`this` reference) to call the `replaceFn` with.
473 *
474 * Defaults to this Autolinker instance.
475 */
476
477
478 /**
479 * @property {String} version (readonly)
480 *
481 * The Autolinker version number in the form major.minor.patch
482 *
483 * Ex: 0.25.1
484 */
485
486 /**
487 * @private
488 * @property {Autolinker.htmlParser.HtmlParser} htmlParser
489 *
490 * The HtmlParser instance used to skip over HTML tags, while finding text
491 * nodes to process. This is lazily instantiated in the {@link #getHtmlParser}
492 * method.
493 */
494
495 /**
496 * @private
497 * @property {Autolinker.matcher.Matcher[]} matchers
498 *
499 * The {@link Autolinker.matcher.Matcher} instances for this Autolinker
500 * instance.
501 *
502 * This is lazily created in {@link #getMatchers}.
503 */
504
505 /**
506 * @private
507 * @property {Autolinker.AnchorTagBuilder} tagBuilder
508 *
509 * The AnchorTagBuilder instance used to build match replacement anchor tags.
510 * Note: this is lazily instantiated in the {@link #getTagBuilder} method.
511 */
512
513
514 /**
515 * Normalizes the {@link #urls} config into an Object with 3 properties:
516 * `schemeMatches`, `wwwMatches`, and `tldMatches`, all Booleans.
517 *
518 * See {@link #urls} config for details.
519 *
520 * @private
521 * @param {Boolean/Object} urls
522 * @return {Object}
523 */
524 normalizeUrlsCfg : function( urls ) {
525 if( urls == null ) urls = true; // default to `true`
526
527 if( typeof urls === 'boolean' ) {
528 return { schemeMatches: urls, wwwMatches: urls, tldMatches: urls };
529
530 } else { // object form
531 return {
532 schemeMatches : typeof urls.schemeMatches === 'boolean' ? urls.schemeMatches : true,
533 wwwMatches : typeof urls.wwwMatches === 'boolean' ? urls.wwwMatches : true,
534 tldMatches : typeof urls.tldMatches === 'boolean' ? urls.tldMatches : true
535 };
536 }
537 },
538
539
540 /**
541 * Normalizes the {@link #stripPrefix} config into an Object with 2
542 * properties: `scheme`, and `www` - both Booleans.
543 *
544 * See {@link #stripPrefix} config for details.
545 *
546 * @private
547 * @param {Boolean/Object} stripPrefix
548 * @return {Object}
549 */
550 normalizeStripPrefixCfg : function( stripPrefix ) {
551 if( stripPrefix == null ) stripPrefix = true; // default to `true`
552
553 if( typeof stripPrefix === 'boolean' ) {
554 return { scheme: stripPrefix, www: stripPrefix };
555
556 } else { // object form
557 return {
558 scheme : typeof stripPrefix.scheme === 'boolean' ? stripPrefix.scheme : true,
559 www : typeof stripPrefix.www === 'boolean' ? stripPrefix.www : true
560 };
561 }
562 },
563
564
565 /**
566 * Normalizes the {@link #truncate} config into an Object with 2 properties:
567 * `length` (Number), and `location` (String).
568 *
569 * See {@link #truncate} config for details.
570 *
571 * @private
572 * @param {Number/Object} truncate
573 * @return {Object}
574 */
575 normalizeTruncateCfg : function( truncate ) {
576 if( typeof truncate === 'number' ) {
577 return { length: truncate, location: 'end' };
578
579 } else { // object, or undefined/null
580 return Autolinker.Util.defaults( truncate || {}, {
581 length : Number.POSITIVE_INFINITY,
582 location : 'end'
583 } );
584 }
585 },
586
587
588 /**
589 * Parses the input `textOrHtml` looking for URLs, email addresses, phone
590 * numbers, username handles, and hashtags (depending on the configuration
591 * of the Autolinker instance), and returns an array of {@link Autolinker.match.Match}
592 * objects describing those matches (without making any replacements).
593 *
594 * This method is used by the {@link #link} method, but can also be used to
595 * simply do parsing of the input in order to discover what kinds of links
596 * there are and how many.
597 *
598 * Example usage:
599 *
600 * var autolinker = new Autolinker( {
601 * urls: true,
602 * email: true
603 * } );
604 *
605 * var matches = autolinker.parse( "Hello google.com, I am [email protected]" );
606 *
607 * console.log( matches.length ); // 2
608 * console.log( matches[ 0 ].getType() ); // 'url'
609 * console.log( matches[ 0 ].getUrl() ); // 'google.com'
610 * console.log( matches[ 1 ].getType() ); // 'email'
611 * console.log( matches[ 1 ].getEmail() ); // '[email protected]'
612 *
613 * @param {String} textOrHtml The HTML or text to find matches within
614 * (depending on if the {@link #urls}, {@link #email}, {@link #phone},
615 * {@link #hashtag}, and {@link #mention} options are enabled).
616 * @return {Autolinker.match.Match[]} The array of Matches found in the
617 * given input `textOrHtml`.
618 */
619 parse : function( textOrHtml ) {
620 var htmlParser = this.getHtmlParser(),
621 htmlNodes = htmlParser.parse( textOrHtml ),
622 anchorTagStackCount = 0, // used to only process text around anchor tags, and any inner text/html they may have;
623 matches = [];
624
625 // Find all matches within the `textOrHtml` (but not matches that are
626 // already nested within <a>, <style> and <script> tags)
627 for( var i = 0, len = htmlNodes.length; i < len; i++ ) {
628 var node = htmlNodes[ i ],
629 nodeType = node.getType();
630
631 if( nodeType === 'element' && ['a', 'style', 'script'].indexOf(node.getTagName()) !== -1 ) { // Process HTML anchor, style and script element nodes in the input `textOrHtml` to find out when we're within an <a>, <style> or <script> tag
632 if( !node.isClosing() ) { // it's the start <a>, <style> or <script> tag
633 anchorTagStackCount++;
634 } else { // it's the end </a>, </style> or </script> tag
635 anchorTagStackCount = Math.max( anchorTagStackCount - 1, 0 ); // attempt to handle extraneous </a> tags by making sure the stack count never goes below 0
636 }
637
638 } else if( nodeType === 'text' && anchorTagStackCount === 0 ) { // Process text nodes that are not within an <a>, <style> and <script> tag
639 var textNodeMatches = this.parseText( node.getText(), node.getOffset() );
640
641 matches.push.apply( matches, textNodeMatches );
642 }
643 }
644
645
646 // After we have found all matches, remove subsequent matches that
647 // overlap with a previous match. This can happen for instance with URLs,
648 // where the url 'google.com/#link' would match '#link' as a hashtag.
649 matches = this.compactMatches( matches );
650
651 // And finally, remove matches for match types that have been turned
652 // off. We needed to have all match types turned on initially so that
653 // things like hashtags could be filtered out if they were really just
654 // part of a URL match (for instance, as a named anchor).
655 matches = this.removeUnwantedMatches( matches );
656
657 return matches;
658 },
659
660
661 /**
662 * After we have found all matches, we need to remove subsequent matches
663 * that overlap with a previous match. This can happen for instance with
664 * URLs, where the url 'google.com/#link' would match '#link' as a hashtag.
665 *
666 * @private
667 * @param {Autolinker.match.Match[]} matches
668 * @return {Autolinker.match.Match[]}
669 */
670 compactMatches : function( matches ) {
671 // First, the matches need to be sorted in order of offset
672 matches.sort( function( a, b ) { return a.getOffset() - b.getOffset(); } );
673
674 for( var i = 0; i < matches.length - 1; i++ ) {
675 var match = matches[ i ],
676 offset = match.getOffset(),
677 matchedTextLength = match.getMatchedText().length,
678 endIdx = offset + matchedTextLength;
679
680 if( i + 1 < matches.length ) {
681 // Remove subsequent matches that equal offset with current match
682 if( matches[ i + 1 ].getOffset() === offset ) {
683 var removeIdx = matches[ i + 1 ].getMatchedText().length > matchedTextLength ? i : i + 1;
684 matches.splice( removeIdx, 1 );
685 continue;
686 }
687
688 // Remove subsequent matches that overlap with the current match
689 if( matches[ i + 1 ].getOffset() < endIdx ) {
690 matches.splice( i + 1, 1 );
691 }
692 }
693 }
694
695 return matches;
696 },
697
698
699 /**
700 * Removes matches for matchers that were turned off in the options. For
701 * example, if {@link #hashtag hashtags} were not to be matched, we'll
702 * remove them from the `matches` array here.
703 *
704 * @private
705 * @param {Autolinker.match.Match[]} matches The array of matches to remove
706 * the unwanted matches from. Note: this array is mutated for the
707 * removals.
708 * @return {Autolinker.match.Match[]} The mutated input `matches` array.
709 */
710 removeUnwantedMatches : function( matches ) {
711 var remove = Autolinker.Util.remove;
712
713 if( !this.hashtag ) remove( matches, function( match ) { return match.getType() === 'hashtag'; } );
714 if( !this.email ) remove( matches, function( match ) { return match.getType() === 'email'; } );
715 if( !this.phone ) remove( matches, function( match ) { return match.getType() === 'phone'; } );
716 if( !this.mention ) remove( matches, function( match ) { return match.getType() === 'mention'; } );
717 if( !this.urls.schemeMatches ) {
718 remove( matches, function( m ) { return m.getType() === 'url' && m.getUrlMatchType() === 'scheme'; } );
719 }
720 if( !this.urls.wwwMatches ) {
721 remove( matches, function( m ) { return m.getType() === 'url' && m.getUrlMatchType() === 'www'; } );
722 }
723 if( !this.urls.tldMatches ) {
724 remove( matches, function( m ) { return m.getType() === 'url' && m.getUrlMatchType() === 'tld'; } );
725 }
726
727 return matches;
728 },
729
730
731 /**
732 * Parses the input `text` looking for URLs, email addresses, phone
733 * numbers, username handles, and hashtags (depending on the configuration
734 * of the Autolinker instance), and returns an array of {@link Autolinker.match.Match}
735 * objects describing those matches.
736 *
737 * This method processes a **non-HTML string**, and is used to parse and
738 * match within the text nodes of an HTML string. This method is used
739 * internally by {@link #parse}.
740 *
741 * @private
742 * @param {String} text The text to find matches within (depending on if the
743 * {@link #urls}, {@link #email}, {@link #phone},
744 * {@link #hashtag}, and {@link #mention} options are enabled). This must be a non-HTML string.
745 * @param {Number} [offset=0] The offset of the text node within the
746 * original string. This is used when parsing with the {@link #parse}
747 * method to generate correct offsets within the {@link Autolinker.match.Match}
748 * instances, but may be omitted if calling this method publicly.
749 * @return {Autolinker.match.Match[]} The array of Matches found in the
750 * given input `text`.
751 */
752 parseText : function( text, offset ) {
753 offset = offset || 0;
754 var matchers = this.getMatchers(),
755 matches = [];
756
757 for( var i = 0, numMatchers = matchers.length; i < numMatchers; i++ ) {
758 var textMatches = matchers[ i ].parseMatches( text );
759
760 // Correct the offset of each of the matches. They are originally
761 // the offset of the match within the provided text node, but we
762 // need to correct them to be relative to the original HTML input
763 // string (i.e. the one provided to #parse).
764 for( var j = 0, numTextMatches = textMatches.length; j < numTextMatches; j++ ) {
765 textMatches[ j ].setOffset( offset + textMatches[ j ].getOffset() );
766 }
767
768 matches.push.apply( matches, textMatches );
769 }
770 return matches;
771 },
772
773
774 /**
775 * Automatically links URLs, Email addresses, Phone numbers, Hashtags,
776 * and Mentions (Twitter, Instagram, Soundcloud) found in the given chunk of HTML. Does not link
777 * URLs found within HTML tags.
778 *
779 * For instance, if given the text: `You should go to http://www.yahoo.com`,
780 * then the result will be `You should go to
781 * &lt;a href="http://www.yahoo.com"&gt;http://www.yahoo.com&lt;/a&gt;`
782 *
783 * This method finds the text around any HTML elements in the input
784 * `textOrHtml`, which will be the text that is processed. Any original HTML
785 * elements will be left as-is, as well as the text that is already wrapped
786 * in anchor (&lt;a&gt;) tags.
787 *
788 * @param {String} textOrHtml The HTML or text to autolink matches within
789 * (depending on if the {@link #urls}, {@link #email}, {@link #phone}, {@link #hashtag}, and {@link #mention} options are enabled).
790 * @return {String} The HTML, with matches automatically linked.
791 */
792 link : function( textOrHtml ) {
793 if( !textOrHtml ) { return ""; } // handle `null` and `undefined`
794
795 var matches = this.parse( textOrHtml ),
796 newHtml = [],
797 lastIndex = 0;
798
799 for( var i = 0, len = matches.length; i < len; i++ ) {
800 var match = matches[ i ];
801
802 newHtml.push( textOrHtml.substring( lastIndex, match.getOffset() ) );
803 newHtml.push( this.createMatchReturnVal( match ) );
804
805 lastIndex = match.getOffset() + match.getMatchedText().length;
806 }
807 newHtml.push( textOrHtml.substring( lastIndex ) ); // handle the text after the last match
808
809 return newHtml.join( '' );
810 },
811
812
813 /**
814 * Creates the return string value for a given match in the input string.
815 *
816 * This method handles the {@link #replaceFn}, if one was provided.
817 *
818 * @private
819 * @param {Autolinker.match.Match} match The Match object that represents
820 * the match.
821 * @return {String} The string that the `match` should be replaced with.
822 * This is usually the anchor tag string, but may be the `matchStr` itself
823 * if the match is not to be replaced.
824 */
825 createMatchReturnVal : function( match ) {
826 // Handle a custom `replaceFn` being provided
827 var replaceFnResult;
828 if( this.replaceFn ) {
829 replaceFnResult = this.replaceFn.call( this.context, match ); // Autolinker instance is the context
830 }
831
832 if( typeof replaceFnResult === 'string' ) {
833 return replaceFnResult; // `replaceFn` returned a string, use that
834
835 } else if( replaceFnResult === false ) {
836 return match.getMatchedText(); // no replacement for the match
837
838 } else if( replaceFnResult instanceof Autolinker.HtmlTag ) {
839 return replaceFnResult.toAnchorString();
840
841 } else { // replaceFnResult === true, or no/unknown return value from function
842 // Perform Autolinker's default anchor tag generation
843 var anchorTag = match.buildTag(); // returns an Autolinker.HtmlTag instance
844
845 return anchorTag.toAnchorString();
846 }
847 },
848
849
850 /**
851 * Lazily instantiates and returns the {@link #htmlParser} instance for this
852 * Autolinker instance.
853 *
854 * @protected
855 * @return {Autolinker.htmlParser.HtmlParser}
856 */
857 getHtmlParser : function() {
858 var htmlParser = this.htmlParser;
859
860 if( !htmlParser ) {
861 htmlParser = this.htmlParser = new Autolinker.htmlParser.HtmlParser();
862 }
863
864 return htmlParser;
865 },
866
867
868 /**
869 * Lazily instantiates and returns the {@link Autolinker.matcher.Matcher}
870 * instances for this Autolinker instance.
871 *
872 * @protected
873 * @return {Autolinker.matcher.Matcher[]}
874 */
875 getMatchers : function() {
876 if( !this.matchers ) {
877 var matchersNs = Autolinker.matcher,
878 tagBuilder = this.getTagBuilder();
879
880 var matchers = [
881 new matchersNs.Hashtag( { tagBuilder: tagBuilder, serviceName: this.hashtag } ),
882 new matchersNs.Email( { tagBuilder: tagBuilder } ),
883 new matchersNs.Phone( { tagBuilder: tagBuilder } ),
884 new matchersNs.Mention( { tagBuilder: tagBuilder, serviceName: this.mention } ),
885 new matchersNs.Url( { tagBuilder: tagBuilder, stripPrefix: this.stripPrefix, stripTrailingSlash: this.stripTrailingSlash, decodePercentEncoding: this.decodePercentEncoding } )
886 ];
887
888 return ( this.matchers = matchers );
889
890 } else {
891 return this.matchers;
892 }
893 },
894
895
896 /**
897 * Returns the {@link #tagBuilder} instance for this Autolinker instance, lazily instantiating it
898 * if it does not yet exist.
899 *
900 * This method may be used in a {@link #replaceFn} to generate the {@link Autolinker.HtmlTag HtmlTag} instance that
901 * Autolinker would normally generate, and then allow for modifications before returning it. For example:
902 *
903 * var html = Autolinker.link( "Test google.com", {
904 * replaceFn : function( match ) {
905 * var tag = match.buildTag(); // returns an {@link Autolinker.HtmlTag} instance
906 * tag.setAttr( 'rel', 'nofollow' );
907 *
908 * return tag;
909 * }
910 * } );
911 *
912 * // generated html:
913 * // Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a>
914 *
915 * @return {Autolinker.AnchorTagBuilder}
916 */
917 getTagBuilder : function() {
918 var tagBuilder = this.tagBuilder;
919
920 if( !tagBuilder ) {
921 tagBuilder = this.tagBuilder = new Autolinker.AnchorTagBuilder( {
922 newWindow : this.newWindow,
923 truncate : this.truncate,
924 className : this.className
925 } );
926 }
927
928 return tagBuilder;
929 }
930
931 };
932
933
934 // Autolinker Namespaces
935
936 Autolinker.match = {};
937 Autolinker.matcher = {};
938 Autolinker.htmlParser = {};
939 Autolinker.truncate = {};
940
941 /*global Autolinker */
942 /*jshint eqnull:true, boss:true */
943 /**
944 * @class Autolinker.Util
945 * @singleton
946 *
947 * A few utility methods for Autolinker.
948 */
949 Autolinker.Util = {
950
951 /**
952 * @property {Function} abstractMethod
953 *
954 * A function object which represents an abstract method.
955 */
956 abstractMethod : function() { throw "abstract"; },
957
958
959 /**
960 * @private
961 * @property {RegExp} trimRegex
962 *
963 * The regular expression used to trim the leading and trailing whitespace
964 * from a string.
965 */
966 trimRegex : /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
967
968
969 /**
970 * Assigns (shallow copies) the properties of `src` onto `dest`.
971 *
972 * @param {Object} dest The destination object.
973 * @param {Object} src The source object.
974 * @return {Object} The destination object (`dest`)
975 */
976 assign : function( dest, src ) {
977 for( var prop in src ) {
978 if( src.hasOwnProperty( prop ) ) {
979 dest[ prop ] = src[ prop ];
980 }
981 }
982
983 return dest;
984 },
985
986
987 /**
988 * Assigns (shallow copies) the properties of `src` onto `dest`, if the
989 * corresponding property on `dest` === `undefined`.
990 *
991 * @param {Object} dest The destination object.
992 * @param {Object} src The source object.
993 * @return {Object} The destination object (`dest`)
994 */
995 defaults : function( dest, src ) {
996 for( var prop in src ) {
997 if( src.hasOwnProperty( prop ) && dest[ prop ] === undefined ) {
998 dest[ prop ] = src[ prop ];
999 }
1000 }
1001
1002 return dest;
1003 },
1004
1005
1006 /**
1007 * Extends `superclass` to create a new subclass, adding the `protoProps` to the new subclass's prototype.
1008 *
1009 * @param {Function} superclass The constructor function for the superclass.
1010 * @param {Object} protoProps The methods/properties to add to the subclass's prototype. This may contain the
1011 * special property `constructor`, which will be used as the new subclass's constructor function.
1012 * @return {Function} The new subclass function.
1013 */
1014 extend : function( superclass, protoProps ) {
1015 var superclassProto = superclass.prototype;
1016
1017 var F = function() {};
1018 F.prototype = superclassProto;
1019
1020 var subclass;
1021 if( protoProps.hasOwnProperty( 'constructor' ) ) {
1022 subclass = protoProps.constructor;
1023 } else {
1024 subclass = function() { superclassProto.constructor.apply( this, arguments ); };
1025 }
1026
1027 var subclassProto = subclass.prototype = new F(); // set up prototype chain
1028 subclassProto.constructor = subclass; // fix constructor property
1029 subclassProto.superclass = superclassProto;
1030
1031 delete protoProps.constructor; // don't re-assign constructor property to the prototype, since a new function may have been created (`subclass`), which is now already there
1032 Autolinker.Util.assign( subclassProto, protoProps );
1033
1034 return subclass;
1035 },
1036
1037
1038 /**
1039 * Truncates the `str` at `len - ellipsisChars.length`, and adds the `ellipsisChars` to the
1040 * end of the string (by default, two periods: '..'). If the `str` length does not exceed
1041 * `len`, the string will be returned unchanged.
1042 *
1043 * @param {String} str The string to truncate and add an ellipsis to.
1044 * @param {Number} truncateLen The length to truncate the string at.
1045 * @param {String} [ellipsisChars=...] The ellipsis character(s) to add to the end of `str`
1046 * when truncated. Defaults to '...'
1047 */
1048 ellipsis : function( str, truncateLen, ellipsisChars ) {
1049 var ellipsisLength;
1050
1051 if( str.length > truncateLen ) {
1052 if(ellipsisChars == null) {
1053 ellipsisChars = '&hellip;';
1054 ellipsisLength = 3;
1055 } else {
1056 ellipsisLength = ellipsisChars.length;
1057 }
1058
1059 str = str.substring( 0, truncateLen - ellipsisLength ) + ellipsisChars;
1060 }
1061 return str;
1062 },
1063
1064
1065 /**
1066 * Supports `Array.prototype.indexOf()` functionality for old IE (IE8 and below).
1067 *
1068 * @param {Array} arr The array to find an element of.
1069 * @param {*} element The element to find in the array, and return the index of.
1070 * @return {Number} The index of the `element`, or -1 if it was not found.
1071 */
1072 indexOf : function( arr, element ) {
1073 if( Array.prototype.indexOf ) {
1074 return arr.indexOf( element );
1075
1076 } else {
1077 for( var i = 0, len = arr.length; i < len; i++ ) {
1078 if( arr[ i ] === element ) return i;
1079 }
1080 return -1;
1081 }
1082 },
1083
1084
1085 /**
1086 * Removes array elements based on a filtering function. Mutates the input
1087 * array.
1088 *
1089 * Using this instead of the ES5 Array.prototype.filter() function, to allow
1090 * Autolinker compatibility with IE8, and also to prevent creating many new
1091 * arrays in memory for filtering.
1092 *
1093 * @param {Array} arr The array to remove elements from. This array is
1094 * mutated.
1095 * @param {Function} fn A function which should return `true` to
1096 * remove an element.
1097 * @return {Array} The mutated input `arr`.
1098 */
1099 remove : function( arr, fn ) {
1100 for( var i = arr.length - 1; i >= 0; i-- ) {
1101 if( fn( arr[ i ] ) === true ) {
1102 arr.splice( i, 1 );
1103 }
1104 }
1105 },
1106
1107
1108 /**
1109 * Performs the functionality of what modern browsers do when `String.prototype.split()` is called
1110 * with a regular expression that contains capturing parenthesis.
1111 *
1112 * For example:
1113 *
1114 * // Modern browsers:
1115 * "a,b,c".split( /(,)/ ); // --> [ 'a', ',', 'b', ',', 'c' ]
1116 *
1117 * // Old IE (including IE8):
1118 * "a,b,c".split( /(,)/ ); // --> [ 'a', 'b', 'c' ]
1119 *
1120 * This method emulates the functionality of modern browsers for the old IE case.
1121 *
1122 * @param {String} str The string to split.
1123 * @param {RegExp} splitRegex The regular expression to split the input `str` on. The splitting
1124 * character(s) will be spliced into the array, as in the "modern browsers" example in the
1125 * description of this method.
1126 * Note #1: the supplied regular expression **must** have the 'g' flag specified.
1127 * Note #2: for simplicity's sake, the regular expression does not need
1128 * to contain capturing parenthesis - it will be assumed that any match has them.
1129 * @return {String[]} The split array of strings, with the splitting character(s) included.
1130 */
1131 splitAndCapture : function( str, splitRegex ) {
1132 if( !splitRegex.global ) throw new Error( "`splitRegex` must have the 'g' flag set" );
1133
1134 var result = [],
1135 lastIdx = 0,
1136 match;
1137
1138 while( match = splitRegex.exec( str ) ) {
1139 result.push( str.substring( lastIdx, match.index ) );
1140 result.push( match[ 0 ] ); // push the splitting char(s)
1141
1142 lastIdx = match.index + match[ 0 ].length;
1143 }
1144 result.push( str.substring( lastIdx ) );
1145
1146 return result;
1147 },
1148
1149
1150 /**
1151 * Trims the leading and trailing whitespace from a string.
1152 *
1153 * @param {String} str The string to trim.
1154 * @return {String}
1155 */
1156 trim : function( str ) {
1157 return str.replace( this.trimRegex, '' );
1158 }
1159
1160 };
1161
1162 /*global Autolinker */
1163 /*jshint boss:true */
1164 /**
1165 * @class Autolinker.HtmlTag
1166 * @extends Object
1167 *
1168 * Represents an HTML tag, which can be used to easily build/modify HTML tags programmatically.
1169 *
1170 * Autolinker uses this abstraction to create HTML tags, and then write them out as strings. You may also use
1171 * this class in your code, especially within a {@link Autolinker#replaceFn replaceFn}.
1172 *
1173 * ## Examples
1174 *
1175 * Example instantiation:
1176 *
1177 * var tag = new Autolinker.HtmlTag( {
1178 * tagName : 'a',
1179 * attrs : { 'href': 'http://google.com', 'class': 'external-link' },
1180 * innerHtml : 'Google'
1181 * } );
1182 *
1183 * tag.toAnchorString(); // <a href="http://google.com" class="external-link">Google</a>
1184 *
1185 * // Individual accessor methods
1186 * tag.getTagName(); // 'a'
1187 * tag.getAttr( 'href' ); // 'http://google.com'
1188 * tag.hasClass( 'external-link' ); // true
1189 *
1190 *
1191 * Using mutator methods (which may be used in combination with instantiation config properties):
1192 *
1193 * var tag = new Autolinker.HtmlTag();
1194 * tag.setTagName( 'a' );
1195 * tag.setAttr( 'href', 'http://google.com' );
1196 * tag.addClass( 'external-link' );
1197 * tag.setInnerHtml( 'Google' );
1198 *
1199 * tag.getTagName(); // 'a'
1200 * tag.getAttr( 'href' ); // 'http://google.com'
1201 * tag.hasClass( 'external-link' ); // true
1202 *
1203 * tag.toAnchorString(); // <a href="http://google.com" class="external-link">Google</a>
1204 *
1205 *
1206 * ## Example use within a {@link Autolinker#replaceFn replaceFn}
1207 *
1208 * var html = Autolinker.link( "Test google.com", {
1209 * replaceFn : function( match ) {
1210 * var tag = match.buildTag(); // returns an {@link Autolinker.HtmlTag} instance, configured with the Match's href and anchor text
1211 * tag.setAttr( 'rel', 'nofollow' );
1212 *
1213 * return tag;
1214 * }
1215 * } );
1216 *
1217 * // generated html:
1218 * // Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a>
1219 *
1220 *
1221 * ## Example use with a new tag for the replacement
1222 *
1223 * var html = Autolinker.link( "Test google.com", {
1224 * replaceFn : function( match ) {
1225 * var tag = new Autolinker.HtmlTag( {
1226 * tagName : 'button',
1227 * attrs : { 'title': 'Load URL: ' + match.getAnchorHref() },
1228 * innerHtml : 'Load URL: ' + match.getAnchorText()
1229 * } );
1230 *
1231 * return tag;
1232 * }
1233 * } );
1234 *
1235 * // generated html:
1236 * // Test <button title="Load URL: http://google.com">Load URL: google.com</button>
1237 */
1238 Autolinker.HtmlTag = Autolinker.Util.extend( Object, {
1239
1240 /**
1241 * @cfg {String} tagName
1242 *
1243 * The tag name. Ex: 'a', 'button', etc.
1244 *
1245 * Not required at instantiation time, but should be set using {@link #setTagName} before {@link #toAnchorString}
1246 * is executed.
1247 */
1248
1249 /**
1250 * @cfg {Object.<String, String>} attrs
1251 *
1252 * An key/value Object (map) of attributes to create the tag with. The keys are the attribute names, and the
1253 * values are the attribute values.
1254 */
1255
1256 /**
1257 * @cfg {String} innerHtml
1258 *
1259 * The inner HTML for the tag.
1260 *
1261 * Note the camel case name on `innerHtml`. Acronyms are camelCased in this utility (such as not to run into the acronym
1262 * naming inconsistency that the DOM developers created with `XMLHttpRequest`). You may alternatively use {@link #innerHTML}
1263 * if you prefer, but this one is recommended.
1264 */
1265
1266 /**
1267 * @cfg {String} innerHTML
1268 *
1269 * Alias of {@link #innerHtml}, accepted for consistency with the browser DOM api, but prefer the camelCased version
1270 * for acronym names.
1271 */
1272
1273
1274 /**
1275 * @protected
1276 * @property {RegExp} whitespaceRegex
1277 *
1278 * Regular expression used to match whitespace in a string of CSS classes.
1279 */
1280 whitespaceRegex : /\s+/,
1281
1282
1283 /**
1284 * @constructor
1285 * @param {Object} [cfg] The configuration properties for this class, in an Object (map)
1286 */
1287 constructor : function( cfg ) {
1288 Autolinker.Util.assign( this, cfg );
1289
1290 this.innerHtml = this.innerHtml || this.innerHTML; // accept either the camelCased form or the fully capitalized acronym
1291 },
1292
1293
1294 /**
1295 * Sets the tag name that will be used to generate the tag with.
1296 *
1297 * @param {String} tagName
1298 * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
1299 */
1300 setTagName : function( tagName ) {
1301 this.tagName = tagName;
1302 return this;
1303 },
1304
1305
1306 /**
1307 * Retrieves the tag name.
1308 *
1309 * @return {String}
1310 */
1311 getTagName : function() {
1312 return this.tagName || "";
1313 },
1314
1315
1316 /**
1317 * Sets an attribute on the HtmlTag.
1318 *
1319 * @param {String} attrName The attribute name to set.
1320 * @param {String} attrValue The attribute value to set.
1321 * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
1322 */
1323 setAttr : function( attrName, attrValue ) {
1324 var tagAttrs = this.getAttrs();
1325 tagAttrs[ attrName ] = attrValue;
1326
1327 return this;
1328 },
1329
1330
1331 /**
1332 * Retrieves an attribute from the HtmlTag. If the attribute does not exist, returns `undefined`.
1333 *
1334 * @param {String} attrName The attribute name to retrieve.
1335 * @return {String} The attribute's value, or `undefined` if it does not exist on the HtmlTag.
1336 */
1337 getAttr : function( attrName ) {
1338 return this.getAttrs()[ attrName ];
1339 },
1340
1341
1342 /**
1343 * Sets one or more attributes on the HtmlTag.
1344 *
1345 * @param {Object.<String, String>} attrs A key/value Object (map) of the attributes to set.
1346 * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
1347 */
1348 setAttrs : function( attrs ) {
1349 var tagAttrs = this.getAttrs();
1350 Autolinker.Util.assign( tagAttrs, attrs );
1351
1352 return this;
1353 },
1354
1355
1356 /**
1357 * Retrieves the attributes Object (map) for the HtmlTag.
1358 *
1359 * @return {Object.<String, String>} A key/value object of the attributes for the HtmlTag.
1360 */
1361 getAttrs : function() {
1362 return this.attrs || ( this.attrs = {} );
1363 },
1364
1365
1366 /**
1367 * Sets the provided `cssClass`, overwriting any current CSS classes on the HtmlTag.
1368 *
1369 * @param {String} cssClass One or more space-separated CSS classes to set (overwrite).
1370 * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
1371 */
1372 setClass : function( cssClass ) {
1373 return this.setAttr( 'class', cssClass );
1374 },
1375
1376
1377 /**
1378 * Convenience method to add one or more CSS classes to the HtmlTag. Will not add duplicate CSS classes.
1379 *
1380 * @param {String} cssClass One or more space-separated CSS classes to add.
1381 * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
1382 */
1383 addClass : function( cssClass ) {
1384 var classAttr = this.getClass(),
1385 whitespaceRegex = this.whitespaceRegex,
1386 indexOf = Autolinker.Util.indexOf, // to support IE8 and below
1387 classes = ( !classAttr ) ? [] : classAttr.split( whitespaceRegex ),
1388 newClasses = cssClass.split( whitespaceRegex ),
1389 newClass;
1390
1391 while( newClass = newClasses.shift() ) {
1392 if( indexOf( classes, newClass ) === -1 ) {
1393 classes.push( newClass );
1394 }
1395 }
1396
1397 this.getAttrs()[ 'class' ] = classes.join( " " );
1398 return this;
1399 },
1400
1401
1402 /**
1403 * Convenience method to remove one or more CSS classes from the HtmlTag.
1404 *
1405 * @param {String} cssClass One or more space-separated CSS classes to remove.
1406 * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
1407 */
1408 removeClass : function( cssClass ) {
1409 var classAttr = this.getClass(),
1410 whitespaceRegex = this.whitespaceRegex,
1411 indexOf = Autolinker.Util.indexOf, // to support IE8 and below
1412 classes = ( !classAttr ) ? [] : classAttr.split( whitespaceRegex ),
1413 removeClasses = cssClass.split( whitespaceRegex ),
1414 removeClass;
1415
1416 while( classes.length && ( removeClass = removeClasses.shift() ) ) {
1417 var idx = indexOf( classes, removeClass );
1418 if( idx !== -1 ) {
1419 classes.splice( idx, 1 );
1420 }
1421 }
1422
1423 this.getAttrs()[ 'class' ] = classes.join( " " );
1424 return this;
1425 },
1426
1427
1428 /**
1429 * Convenience method to retrieve the CSS class(es) for the HtmlTag, which will each be separated by spaces when
1430 * there are multiple.
1431 *
1432 * @return {String}
1433 */
1434 getClass : function() {
1435 return this.getAttrs()[ 'class' ] || "";
1436 },
1437
1438
1439 /**
1440 * Convenience method to check if the tag has a CSS class or not.
1441 *
1442 * @param {String} cssClass The CSS class to check for.
1443 * @return {Boolean} `true` if the HtmlTag has the CSS class, `false` otherwise.
1444 */
1445 hasClass : function( cssClass ) {
1446 return ( ' ' + this.getClass() + ' ' ).indexOf( ' ' + cssClass + ' ' ) !== -1;
1447 },
1448
1449
1450 /**
1451 * Sets the inner HTML for the tag.
1452 *
1453 * @param {String} html The inner HTML to set.
1454 * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained.
1455 */
1456 setInnerHtml : function( html ) {
1457 this.innerHtml = html;
1458
1459 return this;
1460 },
1461
1462
1463 /**
1464 * Retrieves the inner HTML for the tag.
1465 *
1466 * @return {String}
1467 */
1468 getInnerHtml : function() {
1469 return this.innerHtml || "";
1470 },
1471
1472
1473 /**
1474 * Override of superclass method used to generate the HTML string for the tag.
1475 *
1476 * @return {String}
1477 */
1478 toAnchorString : function() {
1479 var tagName = this.getTagName(),
1480 attrsStr = this.buildAttrsStr();
1481
1482 attrsStr = ( attrsStr ) ? ' ' + attrsStr : ''; // prepend a space if there are actually attributes
1483
1484 return [ '<', tagName, attrsStr, '>', this.getInnerHtml(), '</', tagName, '>' ].join( "" );
1485 },
1486
1487
1488 /**
1489 * Support method for {@link #toAnchorString}, returns the string space-separated key="value" pairs, used to populate
1490 * the stringified HtmlTag.
1491 *
1492 * @protected
1493 * @return {String} Example return: `attr1="value1" attr2="value2"`
1494 */
1495 buildAttrsStr : function() {
1496 if( !this.attrs ) return ""; // no `attrs` Object (map) has been set, return empty string
1497
1498 var attrs = this.getAttrs(),
1499 attrsArr = [];
1500
1501 for( var prop in attrs ) {
1502 if( attrs.hasOwnProperty( prop ) ) {
1503 attrsArr.push( prop + '="' + attrs[ prop ] + '"' );
1504 }
1505 }
1506 return attrsArr.join( " " );
1507 }
1508
1509 } );
1510
1511 /*global Autolinker */
1512 /**
1513 * @class Autolinker.RegexLib
1514 * @singleton
1515 *
1516 * Builds and stores a library of the common regular expressions used by the
1517 * Autolinker utility.
1518 *
1519 * Other regular expressions may exist ad-hoc, but these are generally the
1520 * regular expressions that are shared between source files.
1521 */
1522 Autolinker.RegexLib = (function() {
1523
1524 /**
1525 * The string form of a regular expression that would match all of the
1526 * alphabetic ("letter") chars in the unicode character set when placed in a
1527 * RegExp character class (`[]`). This includes all international alphabetic
1528 * characters.
1529 *
1530 * These would be the characters matched by unicode regex engines `\p{L}`
1531 * escape ("all letters").
1532 *
1533 * Taken from the XRegExp library: http://xregexp.com/
1534 * Specifically: http://xregexp.com/v/3.0.0/unicode-categories.js
1535 *
1536 * @private
1537 * @type {String}
1538 */
1539 var alphaCharsStr = 'A-Za-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC';
1540
1541 /**
1542 * The string form of a regular expression that would match all of the
1543 * decimal number chars in the unicode character set when placed in a RegExp
1544 * character class (`[]`).
1545 *
1546 * These would be the characters matched by unicode regex engines `\p{Nd}`
1547 * escape ("all decimal numbers")
1548 *
1549 * Taken from the XRegExp library: http://xregexp.com/
1550 * Specifically: http://xregexp.com/v/3.0.0/unicode-categories.js
1551 *
1552 * @private
1553 * @type {String}
1554 */
1555 var decimalNumbersStr = '0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19';
1556
1557
1558 // See documentation below
1559 var alphaNumericCharsStr = alphaCharsStr + decimalNumbersStr;
1560
1561 // Simplified IP regular expression
1562 var ipStr = '(?:[' + decimalNumbersStr + ']{1,3}\\.){3}[' + decimalNumbersStr + ']{1,3}';
1563
1564 // Protected domain label which do not allow "-" character on the beginning and the end of a single label
1565 var domainLabelStr = '[' + alphaNumericCharsStr + '](?:[' + alphaNumericCharsStr + '\\-]{0,61}[' + alphaNumericCharsStr + '])?';
1566
1567 var getDomainLabelStr = function(group) {
1568 return '(?=(' + domainLabelStr + '))\\' + group;
1569 };
1570
1571 // See documentation below
1572 var getDomainNameStr = function(group) {
1573 return '(?:' + getDomainLabelStr(group) + '(?:\\.' + getDomainLabelStr(group + 1) + '){0,126}|' + ipStr + ')';
1574 };
1575
1576 return {
1577
1578 /**
1579 * The string form of a regular expression that would match all of the
1580 * letters and decimal number chars in the unicode character set when placed
1581 * in a RegExp character class (`[]`).
1582 *
1583 * These would be the characters matched by unicode regex engines `[\p{L}\p{Nd}]`
1584 * escape ("all letters and decimal numbers")
1585 *
1586 * @property {String} alphaNumericCharsStr
1587 */
1588 alphaNumericCharsStr : alphaNumericCharsStr,
1589
1590 /**
1591 * The string form of a regular expression that would match all of the
1592 * letters and in the unicode character set when placed
1593 * in a RegExp character class (`[]`).
1594 *
1595 * These would be the characters matched by unicode regex engines `[\p{L}]`
1596 * escape ("all letters")
1597 *
1598 * @property {String} alphaCharsStr
1599 */
1600 alphaCharsStr : alphaCharsStr,
1601
1602 /**
1603 * A regular expression to match domain names of a URL or email address.
1604 * Ex: 'google', 'yahoo', 'some-other-company', etc.
1605 *
1606 * @property {RegExp} domainNameRegex
1607 */
1608 getDomainNameStr : getDomainNameStr,
1609
1610 };
1611
1612
1613 }() );
1614
1615 /*global Autolinker */
1616 /*jshint sub:true */
1617 /**
1618 * @protected
1619 * @class Autolinker.AnchorTagBuilder
1620 * @extends Object
1621 *
1622 * Builds anchor (&lt;a&gt;) tags for the Autolinker utility when a match is
1623 * found.
1624 *
1625 * Normally this class is instantiated, configured, and used internally by an
1626 * {@link Autolinker} instance, but may actually be used indirectly in a
1627 * {@link Autolinker#replaceFn replaceFn} to create {@link Autolinker.HtmlTag HtmlTag}
1628 * instances which may be modified before returning from the
1629 * {@link Autolinker#replaceFn replaceFn}. For example:
1630 *
1631 * var html = Autolinker.link( "Test google.com", {
1632 * replaceFn : function( match ) {
1633 * var tag = match.buildTag(); // returns an {@link Autolinker.HtmlTag} instance
1634 * tag.setAttr( 'rel', 'nofollow' );
1635 *
1636 * return tag;
1637 * }
1638 * } );
1639 *
1640 * // generated html:
1641 * // Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a>
1642 */
1643 Autolinker.AnchorTagBuilder = Autolinker.Util.extend( Object, {
1644
1645 /**
1646 * @cfg {Boolean} newWindow
1647 * @inheritdoc Autolinker#newWindow
1648 */
1649
1650 /**
1651 * @cfg {Object} truncate
1652 * @inheritdoc Autolinker#truncate
1653 */
1654
1655 /**
1656 * @cfg {String} className
1657 * @inheritdoc Autolinker#className
1658 */
1659
1660
1661 /**
1662 * @constructor
1663 * @param {Object} [cfg] The configuration options for the AnchorTagBuilder instance, specified in an Object (map).
1664 */
1665 constructor : function( cfg ) {
1666 cfg = cfg || {};
1667
1668 this.newWindow = cfg.newWindow;
1669 this.truncate = cfg.truncate;
1670 this.className = cfg.className;
1671 },
1672
1673
1674 /**
1675 * Generates the actual anchor (&lt;a&gt;) tag to use in place of the
1676 * matched text, via its `match` object.
1677 *
1678 * @param {Autolinker.match.Match} match The Match instance to generate an
1679 * anchor tag from.
1680 * @return {Autolinker.HtmlTag} The HtmlTag instance for the anchor tag.
1681 */
1682 build : function( match ) {
1683 return new Autolinker.HtmlTag( {
1684 tagName : 'a',
1685 attrs : this.createAttrs( match ),
1686 innerHtml : this.processAnchorText( match.getAnchorText() )
1687 } );
1688 },
1689
1690
1691 /**
1692 * Creates the Object (map) of the HTML attributes for the anchor (&lt;a&gt;)
1693 * tag being generated.
1694 *
1695 * @protected
1696 * @param {Autolinker.match.Match} match The Match instance to generate an
1697 * anchor tag from.
1698 * @return {Object} A key/value Object (map) of the anchor tag's attributes.
1699 */
1700 createAttrs : function( match ) {
1701 var attrs = {
1702 'href' : match.getAnchorHref() // we'll always have the `href` attribute
1703 };
1704
1705 var cssClass = this.createCssClass( match );
1706 if( cssClass ) {
1707 attrs[ 'class' ] = cssClass;
1708 }
1709 if( this.newWindow ) {
1710 attrs[ 'target' ] = "_blank";
1711 attrs[ 'rel' ] = "noopener noreferrer";
1712 }
1713
1714 if( this.truncate ) {
1715 if( this.truncate.length && this.truncate.length < match.getAnchorText().length ) {
1716 attrs[ 'title' ] = match.getAnchorHref();
1717 }
1718 }
1719
1720 return attrs;
1721 },
1722
1723
1724 /**
1725 * Creates the CSS class that will be used for a given anchor tag, based on
1726 * the `matchType` and the {@link #className} config.
1727 *
1728 * Example returns:
1729 *
1730 * - "" // no {@link #className}
1731 * - "myLink myLink-url" // url match
1732 * - "myLink myLink-email" // email match
1733 * - "myLink myLink-phone" // phone match
1734 * - "myLink myLink-hashtag" // hashtag match
1735 * - "myLink myLink-mention myLink-twitter" // mention match with Twitter service
1736 *
1737 * @private
1738 * @param {Autolinker.match.Match} match The Match instance to generate an
1739 * anchor tag from.
1740 * @return {String} The CSS class string for the link. Example return:
1741 * "myLink myLink-url". If no {@link #className} was configured, returns
1742 * an empty string.
1743 */
1744 createCssClass : function( match ) {
1745 var className = this.className;
1746
1747 if( !className ) {
1748 return "";
1749
1750 } else {
1751 var returnClasses = [ className ],
1752 cssClassSuffixes = match.getCssClassSuffixes();
1753
1754 for( var i = 0, len = cssClassSuffixes.length; i < len; i++ ) {
1755 returnClasses.push( className + '-' + cssClassSuffixes[ i ] );
1756 }
1757 return returnClasses.join( ' ' );
1758 }
1759 },
1760
1761
1762 /**
1763 * Processes the `anchorText` by truncating the text according to the
1764 * {@link #truncate} config.
1765 *
1766 * @private
1767 * @param {String} anchorText The anchor tag's text (i.e. what will be
1768 * displayed).
1769 * @return {String} The processed `anchorText`.
1770 */
1771 processAnchorText : function( anchorText ) {
1772 anchorText = this.doTruncate( anchorText );
1773
1774 return anchorText;
1775 },
1776
1777
1778 /**
1779 * Performs the truncation of the `anchorText` based on the {@link #truncate}
1780 * option. If the `anchorText` is longer than the length specified by the
1781 * {@link #truncate} option, the truncation is performed based on the
1782 * `location` property. See {@link #truncate} for details.
1783 *
1784 * @private
1785 * @param {String} anchorText The anchor tag's text (i.e. what will be
1786 * displayed).
1787 * @return {String} The truncated anchor text.
1788 */
1789 doTruncate : function( anchorText ) {
1790 var truncate = this.truncate;
1791 if( !truncate || !truncate.length ) return anchorText;
1792
1793 var truncateLength = truncate.length,
1794 truncateLocation = truncate.location;
1795
1796 if( truncateLocation === 'smart' ) {
1797 return Autolinker.truncate.TruncateSmart( anchorText, truncateLength );
1798
1799 } else if( truncateLocation === 'middle' ) {
1800 return Autolinker.truncate.TruncateMiddle( anchorText, truncateLength );
1801
1802 } else {
1803 return Autolinker.truncate.TruncateEnd( anchorText, truncateLength );
1804 }
1805 }
1806
1807 } );
1808
1809 /*global Autolinker */
1810 /**
1811 * @class Autolinker.htmlParser.HtmlParser
1812 * @extends Object
1813 *
1814 * An HTML parser implementation which simply walks an HTML string and returns an array of
1815 * {@link Autolinker.htmlParser.HtmlNode HtmlNodes} that represent the basic HTML structure of the input string.
1816 *
1817 * Autolinker uses this to only link URLs/emails/mentions within text nodes, effectively ignoring / "walking
1818 * around" HTML tags.
1819 */
1820 Autolinker.htmlParser.HtmlParser = Autolinker.Util.extend( Object, {
1821
1822 /**
1823 * @private
1824 * @property {RegExp} htmlRegex
1825 *
1826 * The regular expression used to pull out HTML tags from a string. Handles namespaced HTML tags and
1827 * attribute names, as specified by http://www.w3.org/TR/html-markup/syntax.html.
1828 *
1829 * Capturing groups:
1830 *
1831 * 1. The "!DOCTYPE" tag name, if a tag is a &lt;!DOCTYPE&gt; tag.
1832 * 2. If it is an end tag, this group will have the '/'.
1833 * 3. If it is a comment tag, this group will hold the comment text (i.e.
1834 * the text inside the `&lt;!--` and `--&gt;`.
1835 * 4. The tag name for a tag without attributes (other than the &lt;!DOCTYPE&gt; tag)
1836 * 5. The tag name for a tag with attributes (other than the &lt;!DOCTYPE&gt; tag)
1837 */
1838 htmlRegex : (function() {
1839 var commentTagRegex = /!--([\s\S]+?)--/,
1840 tagNameRegex = /[0-9a-zA-Z][0-9a-zA-Z:]*/,
1841 attrNameRegex = /[^\s"'>\/=\x00-\x1F\x7F]+/, // the unicode range accounts for excluding control chars, and the delete char
1842 attrValueRegex = /(?:"[^"]*?"|'[^']*?'|[^'"=<>`\s]+)/, // double quoted, single quoted, or unquoted attribute values
1843 optionalAttrValueRegex = '(?:\\s*?=\\s*?' + attrValueRegex.source + ')?'; // optional '=[value]'
1844
1845 var getNameEqualsValueRegex = function(group) {
1846 return '(?=(' + attrNameRegex.source + '))\\' + group + optionalAttrValueRegex;
1847 };
1848
1849 return new RegExp( [
1850 // for <!DOCTYPE> tag. Ex: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">)
1851 '(?:',
1852 '<(!DOCTYPE)', // *** Capturing Group 1 - If it's a doctype tag
1853
1854 // Zero or more attributes following the tag name
1855 '(?:',
1856 '\\s+', // one or more whitespace chars before an attribute
1857
1858 // Either:
1859 // A. attr="value", or
1860 // B. "value" alone (To cover example doctype tag: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">)
1861 // *** Capturing Group 2 - Pseudo-atomic group for attrNameRegex
1862 '(?:', getNameEqualsValueRegex(2), '|', attrValueRegex.source + ')',
1863 ')*',
1864 '>',
1865 ')',
1866
1867 '|',
1868
1869 // All other HTML tags (i.e. tags that are not <!DOCTYPE>)
1870 '(?:',
1871 '<(/)?', // Beginning of a tag or comment. Either '<' for a start tag, or '</' for an end tag.
1872 // *** Capturing Group 3: The slash or an empty string. Slash ('/') for end tag, empty string for start or self-closing tag.
1873
1874 '(?:',
1875 commentTagRegex.source, // *** Capturing Group 4 - A Comment Tag's Text
1876
1877 '|',
1878
1879 // Handle tag without attributes.
1880 // Doing this separately from a tag that has attributes
1881 // to fix a regex time complexity issue seen with the
1882 // example in https://github.com/gregjacobs/Autolinker.js/issues/172
1883 '(?:',
1884 // *** Capturing Group 5 - The tag name for a tag without attributes
1885 '(' + tagNameRegex.source + ')',
1886
1887 '\\s*/?', // any trailing spaces and optional '/' before the closing '>'
1888 ')',
1889
1890 '|',
1891
1892 // Handle tag with attributes
1893 // Doing this separately from a tag with no attributes
1894 // to fix a regex time complexity issue seen with the
1895 // example in https://github.com/gregjacobs/Autolinker.js/issues/172
1896 '(?:',
1897 // *** Capturing Group 6 - The tag name for a tag with attributes
1898 '(' + tagNameRegex.source + ')',
1899
1900 '\\s+', // must have at least one space after the tag name to prevent ReDoS issue (issue #172)
1901
1902 // Zero or more attributes following the tag name
1903 '(?:',
1904 '(?:\\s+|\\b)', // any number of whitespace chars before an attribute. NOTE: Using \s* here throws Chrome into an infinite loop for some reason, so using \s+|\b instead
1905 // *** Capturing Group 7 - Pseudo-atomic group for attrNameRegex
1906 getNameEqualsValueRegex(7), // attr="value" (with optional ="value" part)
1907 ')*',
1908
1909 '\\s*/?', // any trailing spaces and optional '/' before the closing '>'
1910 ')',
1911 ')',
1912 '>',
1913 ')'
1914 ].join( "" ), 'gi' );
1915 } )(),
1916
1917 /**
1918 * @private
1919 * @property {RegExp} htmlCharacterEntitiesRegex
1920 *
1921 * The regular expression that matches common HTML character entities.
1922 *
1923 * Ignoring &amp; as it could be part of a query string -- handling it separately.
1924 */
1925 htmlCharacterEntitiesRegex: /(&nbsp;|&#160;|&lt;|&#60;|&gt;|&#62;|&quot;|&#34;|&#39;)/gi,
1926
1927
1928 /**
1929 * Parses an HTML string and returns a simple array of {@link Autolinker.htmlParser.HtmlNode HtmlNodes}
1930 * to represent the HTML structure of the input string.
1931 *
1932 * @param {String} html The HTML to parse.
1933 * @return {Autolinker.htmlParser.HtmlNode[]}
1934 */
1935 parse : function( html ) {
1936 var htmlRegex = this.htmlRegex,
1937 currentResult,
1938 lastIndex = 0,
1939 textAndEntityNodes,
1940 nodes = []; // will be the result of the method
1941
1942 while( ( currentResult = htmlRegex.exec( html ) ) !== null ) {
1943 var tagText = currentResult[ 0 ],
1944 commentText = currentResult[ 4 ], // if we've matched a comment
1945 tagName = currentResult[ 1 ] || currentResult[ 5 ] || currentResult[ 6 ], // The <!DOCTYPE> tag (ex: "!DOCTYPE"), or another tag (ex: "a" or "img")
1946 isClosingTag = !!currentResult[ 3 ],
1947 offset = currentResult.index,
1948 inBetweenTagsText = html.substring( lastIndex, offset );
1949
1950 // Push TextNodes and EntityNodes for any text found between tags
1951 if( inBetweenTagsText ) {
1952 textAndEntityNodes = this.parseTextAndEntityNodes( lastIndex, inBetweenTagsText );
1953 nodes.push.apply( nodes, textAndEntityNodes );
1954 }
1955
1956 // Push the CommentNode or ElementNode
1957 if( commentText ) {
1958 nodes.push( this.createCommentNode( offset, tagText, commentText ) );
1959 } else {
1960 nodes.push( this.createElementNode( offset, tagText, tagName, isClosingTag ) );
1961 }
1962
1963 lastIndex = offset + tagText.length;
1964 }
1965
1966 // Process any remaining text after the last HTML element. Will process all of the text if there were no HTML elements.
1967 if( lastIndex < html.length ) {
1968 var text = html.substring( lastIndex );
1969
1970 // Push TextNodes and EntityNodes for any text found between tags
1971 if( text ) {
1972 textAndEntityNodes = this.parseTextAndEntityNodes( lastIndex, text );
1973
1974 // Note: the following 3 lines were previously:
1975 // nodes.push.apply( nodes, textAndEntityNodes );
1976 // but this was causing a "Maximum Call Stack Size Exceeded"
1977 // error on inputs with a large number of html entities.
1978 textAndEntityNodes.forEach( function( node ) {
1979 nodes.push( node );
1980 } );
1981 }
1982 }
1983
1984 return nodes;
1985 },
1986
1987
1988 /**
1989 * Parses text and HTML entity nodes from a given string. The input string
1990 * should not have any HTML tags (elements) within it.
1991 *
1992 * @private
1993 * @param {Number} offset The offset of the text node match within the
1994 * original HTML string.
1995 * @param {String} text The string of text to parse. This is from an HTML
1996 * text node.
1997 * @return {Autolinker.htmlParser.HtmlNode[]} An array of HtmlNodes to
1998 * represent the {@link Autolinker.htmlParser.TextNode TextNodes} and
1999 * {@link Autolinker.htmlParser.EntityNode EntityNodes} found.
2000 */
2001 parseTextAndEntityNodes : function( offset, text ) {
2002 var nodes = [],
2003 textAndEntityTokens = Autolinker.Util.splitAndCapture( text, this.htmlCharacterEntitiesRegex ); // split at HTML entities, but include the HTML entities in the results array
2004
2005 // Every even numbered token is a TextNode, and every odd numbered token is an EntityNode
2006 // For example: an input `text` of "Test &quot;this&quot; today" would turn into the
2007 // `textAndEntityTokens`: [ 'Test ', '&quot;', 'this', '&quot;', ' today' ]
2008 for( var i = 0, len = textAndEntityTokens.length; i < len; i += 2 ) {
2009 var textToken = textAndEntityTokens[ i ],
2010 entityToken = textAndEntityTokens[ i + 1 ];
2011
2012 if( textToken ) {
2013 nodes.push( this.createTextNode( offset, textToken ) );
2014 offset += textToken.length;
2015 }
2016 if( entityToken ) {
2017 nodes.push( this.createEntityNode( offset, entityToken ) );
2018 offset += entityToken.length;
2019 }
2020 }
2021 return nodes;
2022 },
2023
2024
2025 /**
2026 * Factory method to create an {@link Autolinker.htmlParser.CommentNode CommentNode}.
2027 *
2028 * @private
2029 * @param {Number} offset The offset of the match within the original HTML
2030 * string.
2031 * @param {String} tagText The full text of the tag (comment) that was
2032 * matched, including its &lt;!-- and --&gt;.
2033 * @param {String} commentText The full text of the comment that was matched.
2034 */
2035 createCommentNode : function( offset, tagText, commentText ) {
2036 return new Autolinker.htmlParser.CommentNode( {
2037 offset : offset,
2038 text : tagText,
2039 comment: Autolinker.Util.trim( commentText )
2040 } );
2041 },
2042
2043
2044 /**
2045 * Factory method to create an {@link Autolinker.htmlParser.ElementNode ElementNode}.
2046 *
2047 * @private
2048 * @param {Number} offset The offset of the match within the original HTML
2049 * string.
2050 * @param {String} tagText The full text of the tag (element) that was
2051 * matched, including its attributes.
2052 * @param {String} tagName The name of the tag. Ex: An &lt;img&gt; tag would
2053 * be passed to this method as "img".
2054 * @param {Boolean} isClosingTag `true` if it's a closing tag, false
2055 * otherwise.
2056 * @return {Autolinker.htmlParser.ElementNode}
2057 */
2058 createElementNode : function( offset, tagText, tagName, isClosingTag ) {
2059 return new Autolinker.htmlParser.ElementNode( {
2060 offset : offset,
2061 text : tagText,
2062 tagName : tagName.toLowerCase(),
2063 closing : isClosingTag
2064 } );
2065 },
2066
2067
2068 /**
2069 * Factory method to create a {@link Autolinker.htmlParser.EntityNode EntityNode}.
2070 *
2071 * @private
2072 * @param {Number} offset The offset of the match within the original HTML
2073 * string.
2074 * @param {String} text The text that was matched for the HTML entity (such
2075 * as '&amp;nbsp;').
2076 * @return {Autolinker.htmlParser.EntityNode}
2077 */
2078 createEntityNode : function( offset, text ) {
2079 return new Autolinker.htmlParser.EntityNode( { offset: offset, text: text } );
2080 },
2081
2082
2083 /**
2084 * Factory method to create a {@link Autolinker.htmlParser.TextNode TextNode}.
2085 *
2086 * @private
2087 * @param {Number} offset The offset of the match within the original HTML
2088 * string.
2089 * @param {String} text The text that was matched.
2090 * @return {Autolinker.htmlParser.TextNode}
2091 */
2092 createTextNode : function( offset, text ) {
2093 return new Autolinker.htmlParser.TextNode( { offset: offset, text: text } );
2094 }
2095
2096 } );
2097
2098 /*global Autolinker */
2099 /**
2100 * @abstract
2101 * @class Autolinker.htmlParser.HtmlNode
2102 *
2103 * Represents an HTML node found in an input string. An HTML node is one of the
2104 * following:
2105 *
2106 * 1. An {@link Autolinker.htmlParser.ElementNode ElementNode}, which represents
2107 * HTML tags.
2108 * 2. A {@link Autolinker.htmlParser.CommentNode CommentNode}, which represents
2109 * HTML comments.
2110 * 3. A {@link Autolinker.htmlParser.TextNode TextNode}, which represents text
2111 * outside or within HTML tags.
2112 * 4. A {@link Autolinker.htmlParser.EntityNode EntityNode}, which represents
2113 * one of the known HTML entities that Autolinker looks for. This includes
2114 * common ones such as &amp;quot; and &amp;nbsp;
2115 */
2116 Autolinker.htmlParser.HtmlNode = Autolinker.Util.extend( Object, {
2117
2118 /**
2119 * @cfg {Number} offset (required)
2120 *
2121 * The offset of the HTML node in the original text that was parsed.
2122 */
2123 offset : undefined,
2124
2125 /**
2126 * @cfg {String} text (required)
2127 *
2128 * The text that was matched for the HtmlNode.
2129 *
2130 * - In the case of an {@link Autolinker.htmlParser.ElementNode ElementNode},
2131 * this will be the tag's text.
2132 * - In the case of an {@link Autolinker.htmlParser.CommentNode CommentNode},
2133 * this will be the comment's text.
2134 * - In the case of a {@link Autolinker.htmlParser.TextNode TextNode}, this
2135 * will be the text itself.
2136 * - In the case of a {@link Autolinker.htmlParser.EntityNode EntityNode},
2137 * this will be the text of the HTML entity.
2138 */
2139 text : undefined,
2140
2141
2142 /**
2143 * @constructor
2144 * @param {Object} cfg The configuration properties for the Match instance,
2145 * specified in an Object (map).
2146 */
2147 constructor : function( cfg ) {
2148 Autolinker.Util.assign( this, cfg );
2149
2150 if( this.offset == null ) throw new Error( '`offset` cfg required' );
2151 if( this.text == null ) throw new Error( '`text` cfg required' );
2152 },
2153
2154
2155 /**
2156 * Returns a string name for the type of node that this class represents.
2157 *
2158 * @abstract
2159 * @return {String}
2160 */
2161 getType : Autolinker.Util.abstractMethod,
2162
2163
2164 /**
2165 * Retrieves the {@link #offset} of the HtmlNode. This is the offset of the
2166 * HTML node in the original string that was parsed.
2167 *
2168 * @return {Number}
2169 */
2170 getOffset : function() {
2171 return this.offset;
2172 },
2173
2174
2175 /**
2176 * Retrieves the {@link #text} for the HtmlNode.
2177 *
2178 * @return {String}
2179 */
2180 getText : function() {
2181 return this.text;
2182 }
2183
2184 } );
2185 /*global Autolinker */
2186 /**
2187 * @class Autolinker.htmlParser.CommentNode
2188 * @extends Autolinker.htmlParser.HtmlNode
2189 *
2190 * Represents an HTML comment node that has been parsed by the
2191 * {@link Autolinker.htmlParser.HtmlParser}.
2192 *
2193 * See this class's superclass ({@link Autolinker.htmlParser.HtmlNode}) for more
2194 * details.
2195 */
2196 Autolinker.htmlParser.CommentNode = Autolinker.Util.extend( Autolinker.htmlParser.HtmlNode, {
2197
2198 /**
2199 * @cfg {String} comment (required)
2200 *
2201 * The text inside the comment tag. This text is stripped of any leading or
2202 * trailing whitespace.
2203 */
2204 comment : '',
2205
2206
2207 /**
2208 * Returns a string name for the type of node that this class represents.
2209 *
2210 * @return {String}
2211 */
2212 getType : function() {
2213 return 'comment';
2214 },
2215
2216
2217 /**
2218 * Returns the comment inside the comment tag.
2219 *
2220 * @return {String}
2221 */
2222 getComment : function() {
2223 return this.comment;
2224 }
2225
2226 } );
2227 /*global Autolinker */
2228 /**
2229 * @class Autolinker.htmlParser.ElementNode
2230 * @extends Autolinker.htmlParser.HtmlNode
2231 *
2232 * Represents an HTML element node that has been parsed by the {@link Autolinker.htmlParser.HtmlParser}.
2233 *
2234 * See this class's superclass ({@link Autolinker.htmlParser.HtmlNode}) for more
2235 * details.
2236 */
2237 Autolinker.htmlParser.ElementNode = Autolinker.Util.extend( Autolinker.htmlParser.HtmlNode, {
2238
2239 /**
2240 * @cfg {String} tagName (required)
2241 *
2242 * The name of the tag that was matched.
2243 */
2244 tagName : '',
2245
2246 /**
2247 * @cfg {Boolean} closing (required)
2248 *
2249 * `true` if the element (tag) is a closing tag, `false` if its an opening
2250 * tag.
2251 */
2252 closing : false,
2253
2254
2255 /**
2256 * Returns a string name for the type of node that this class represents.
2257 *
2258 * @return {String}
2259 */
2260 getType : function() {
2261 return 'element';
2262 },
2263
2264
2265 /**
2266 * Returns the HTML element's (tag's) name. Ex: for an &lt;img&gt; tag,
2267 * returns "img".
2268 *
2269 * @return {String}
2270 */
2271 getTagName : function() {
2272 return this.tagName;
2273 },
2274
2275
2276 /**
2277 * Determines if the HTML element (tag) is a closing tag. Ex: &lt;div&gt;
2278 * returns `false`, while &lt;/div&gt; returns `true`.
2279 *
2280 * @return {Boolean}
2281 */
2282 isClosing : function() {
2283 return this.closing;
2284 }
2285
2286 } );
2287 /*global Autolinker */
2288 /**
2289 * @class Autolinker.htmlParser.EntityNode
2290 * @extends Autolinker.htmlParser.HtmlNode
2291 *
2292 * Represents a known HTML entity node that has been parsed by the {@link Autolinker.htmlParser.HtmlParser}.
2293 * Ex: '&amp;nbsp;', or '&amp#160;' (which will be retrievable from the {@link #getText}
2294 * method.
2295 *
2296 * Note that this class will only be returned from the HtmlParser for the set of
2297 * checked HTML entity nodes defined by the {@link Autolinker.htmlParser.HtmlParser#htmlCharacterEntitiesRegex}.
2298 *
2299 * See this class's superclass ({@link Autolinker.htmlParser.HtmlNode}) for more
2300 * details.
2301 */
2302 Autolinker.htmlParser.EntityNode = Autolinker.Util.extend( Autolinker.htmlParser.HtmlNode, {
2303
2304 /**
2305 * Returns a string name for the type of node that this class represents.
2306 *
2307 * @return {String}
2308 */
2309 getType : function() {
2310 return 'entity';
2311 }
2312
2313 } );
2314 /*global Autolinker */
2315 /**
2316 * @class Autolinker.htmlParser.TextNode
2317 * @extends Autolinker.htmlParser.HtmlNode
2318 *
2319 * Represents a text node that has been parsed by the {@link Autolinker.htmlParser.HtmlParser}.
2320 *
2321 * See this class's superclass ({@link Autolinker.htmlParser.HtmlNode}) for more
2322 * details.
2323 */
2324 Autolinker.htmlParser.TextNode = Autolinker.Util.extend( Autolinker.htmlParser.HtmlNode, {
2325
2326 /**
2327 * Returns a string name for the type of node that this class represents.
2328 *
2329 * @return {String}
2330 */
2331 getType : function() {
2332 return 'text';
2333 }
2334
2335 } );
2336 /*global Autolinker */
2337 /**
2338 * @abstract
2339 * @class Autolinker.match.Match
2340 *
2341 * Represents a match found in an input string which should be Autolinked. A Match object is what is provided in a
2342 * {@link Autolinker#replaceFn replaceFn}, and may be used to query for details about the match.
2343 *
2344 * For example:
2345 *
2346 * var input = "..."; // string with URLs, Email Addresses, and Mentions (Twitter, Instagram, Soundcloud)
2347 *
2348 * var linkedText = Autolinker.link( input, {
2349 * replaceFn : function( match ) {
2350 * console.log( "href = ", match.getAnchorHref() );
2351 * console.log( "text = ", match.getAnchorText() );
2352 *
2353 * switch( match.getType() ) {
2354 * case 'url' :
2355 * console.log( "url: ", match.getUrl() );
2356 *
2357 * case 'email' :
2358 * console.log( "email: ", match.getEmail() );
2359 *
2360 * case 'mention' :
2361 * console.log( "mention: ", match.getMention() );
2362 * }
2363 * }
2364 * } );
2365 *
2366 * See the {@link Autolinker} class for more details on using the {@link Autolinker#replaceFn replaceFn}.
2367 */
2368 Autolinker.match.Match = Autolinker.Util.extend( Object, {
2369
2370 /**
2371 * @cfg {Autolinker.AnchorTagBuilder} tagBuilder (required)
2372 *
2373 * Reference to the AnchorTagBuilder instance to use to generate an anchor
2374 * tag for the Match.
2375 */
2376
2377 /**
2378 * @cfg {String} matchedText (required)
2379 *
2380 * The original text that was matched by the {@link Autolinker.matcher.Matcher}.
2381 */
2382
2383 /**
2384 * @cfg {Number} offset (required)
2385 *
2386 * The offset of where the match was made in the input string.
2387 */
2388
2389
2390 /**
2391 * @constructor
2392 * @param {Object} cfg The configuration properties for the Match
2393 * instance, specified in an Object (map).
2394 */
2395 constructor : function( cfg ) {
2396 if( cfg.tagBuilder == null ) throw new Error( '`tagBuilder` cfg required' );
2397 if( cfg.matchedText == null ) throw new Error( '`matchedText` cfg required' );
2398 if( cfg.offset == null ) throw new Error( '`offset` cfg required' );
2399
2400 this.tagBuilder = cfg.tagBuilder;
2401 this.matchedText = cfg.matchedText;
2402 this.offset = cfg.offset;
2403 },
2404
2405
2406 /**
2407 * Returns a string name for the type of match that this class represents.
2408 *
2409 * @abstract
2410 * @return {String}
2411 */
2412 getType : Autolinker.Util.abstractMethod,
2413
2414
2415 /**
2416 * Returns the original text that was matched.
2417 *
2418 * @return {String}
2419 */
2420 getMatchedText : function() {
2421 return this.matchedText;
2422 },
2423
2424
2425 /**
2426 * Sets the {@link #offset} of where the match was made in the input string.
2427 *
2428 * A {@link Autolinker.matcher.Matcher} will be fed only HTML text nodes,
2429 * and will therefore set an original offset that is relative to the HTML
2430 * text node itself. However, we want this offset to be relative to the full
2431 * HTML input string, and thus if using {@link Autolinker#parse} (rather
2432 * than calling a {@link Autolinker.matcher.Matcher} directly), then this
2433 * offset is corrected after the Matcher itself has done its job.
2434 *
2435 * @param {Number} offset
2436 */
2437 setOffset : function( offset ) {
2438 this.offset = offset;
2439 },
2440
2441
2442 /**
2443 * Returns the offset of where the match was made in the input string. This
2444 * is the 0-based index of the match.
2445 *
2446 * @return {Number}
2447 */
2448 getOffset : function() {
2449 return this.offset;
2450 },
2451
2452
2453 /**
2454 * Returns the anchor href that should be generated for the match.
2455 *
2456 * @abstract
2457 * @return {String}
2458 */
2459 getAnchorHref : Autolinker.Util.abstractMethod,
2460
2461
2462 /**
2463 * Returns the anchor text that should be generated for the match.
2464 *
2465 * @abstract
2466 * @return {String}
2467 */
2468 getAnchorText : Autolinker.Util.abstractMethod,
2469
2470
2471 /**
2472 * Returns the CSS class suffix(es) for this match.
2473 *
2474 * A CSS class suffix is appended to the {@link Autolinker#className} in
2475 * the {@link Autolinker.AnchorTagBuilder} when a match is translated into
2476 * an anchor tag.
2477 *
2478 * For example, if {@link Autolinker#className} was configured as 'myLink',
2479 * and this method returns `[ 'url' ]`, the final class name of the element
2480 * will become: 'myLink myLink-url'.
2481 *
2482 * The match may provide multiple CSS class suffixes to be appended to the
2483 * {@link Autolinker#className} in order to facilitate better styling
2484 * options for different match criteria. See {@link Autolinker.match.Mention}
2485 * for an example.
2486 *
2487 * By default, this method returns a single array with the match's
2488 * {@link #getType type} name, but may be overridden by subclasses.
2489 *
2490 * @return {String[]}
2491 */
2492 getCssClassSuffixes : function() {
2493 return [ this.getType() ];
2494 },
2495
2496
2497 /**
2498 * Builds and returns an {@link Autolinker.HtmlTag} instance based on the
2499 * Match.
2500 *
2501 * This can be used to easily generate anchor tags from matches, and either
2502 * return their HTML string, or modify them before doing so.
2503 *
2504 * Example Usage:
2505 *
2506 * var tag = match.buildTag();
2507 * tag.addClass( 'cordova-link' );
2508 * tag.setAttr( 'target', '_system' );
2509 *
2510 * tag.toAnchorString(); // <a href="http://google.com" class="cordova-link" target="_system">Google</a>
2511 */
2512 buildTag : function() {
2513 return this.tagBuilder.build( this );
2514 }
2515
2516 } );
2517
2518 /*global Autolinker */
2519 /**
2520 * @class Autolinker.match.Email
2521 * @extends Autolinker.match.Match
2522 *
2523 * Represents a Email match found in an input string which should be Autolinked.
2524 *
2525 * See this class's superclass ({@link Autolinker.match.Match}) for more details.
2526 */
2527 Autolinker.match.Email = Autolinker.Util.extend( Autolinker.match.Match, {
2528
2529 /**
2530 * @cfg {String} email (required)
2531 *
2532 * The email address that was matched.
2533 */
2534
2535
2536 /**
2537 * @constructor
2538 * @param {Object} cfg The configuration properties for the Match
2539 * instance, specified in an Object (map).
2540 */
2541 constructor : function( cfg ) {
2542 Autolinker.match.Match.prototype.constructor.call( this, cfg );
2543
2544 if( !cfg.email ) throw new Error( '`email` cfg required' );
2545
2546 this.email = cfg.email;
2547 },
2548
2549
2550 /**
2551 * Returns a string name for the type of match that this class represents.
2552 *
2553 * @return {String}
2554 */
2555 getType : function() {
2556 return 'email';
2557 },
2558
2559
2560 /**
2561 * Returns the email address that was matched.
2562 *
2563 * @return {String}
2564 */
2565 getEmail : function() {
2566 return this.email;
2567 },
2568
2569
2570 /**
2571 * Returns the anchor href that should be generated for the match.
2572 *
2573 * @return {String}
2574 */
2575 getAnchorHref : function() {
2576 return 'mailto:' + this.email;
2577 },
2578
2579
2580 /**
2581 * Returns the anchor text that should be generated for the match.
2582 *
2583 * @return {String}
2584 */
2585 getAnchorText : function() {
2586 return this.email;
2587 }
2588
2589 } );
2590 /*global Autolinker */
2591 /**
2592 * @class Autolinker.match.Hashtag
2593 * @extends Autolinker.match.Match
2594 *
2595 * Represents a Hashtag match found in an input string which should be
2596 * Autolinked.
2597 *
2598 * See this class's superclass ({@link Autolinker.match.Match}) for more
2599 * details.
2600 */
2601 Autolinker.match.Hashtag = Autolinker.Util.extend( Autolinker.match.Match, {
2602
2603 /**
2604 * @cfg {String} serviceName
2605 *
2606 * The service to point hashtag matches to. See {@link Autolinker#hashtag}
2607 * for available values.
2608 */
2609
2610 /**
2611 * @cfg {String} hashtag (required)
2612 *
2613 * The Hashtag that was matched, without the '#'.
2614 */
2615
2616
2617 /**
2618 * @constructor
2619 * @param {Object} cfg The configuration properties for the Match
2620 * instance, specified in an Object (map).
2621 */
2622 constructor : function( cfg ) {
2623 Autolinker.match.Match.prototype.constructor.call( this, cfg );
2624
2625 // TODO: if( !serviceName ) throw new Error( '`serviceName` cfg required' );
2626 if( !cfg.hashtag ) throw new Error( '`hashtag` cfg required' );
2627
2628 this.serviceName = cfg.serviceName;
2629 this.hashtag = cfg.hashtag;
2630 },
2631
2632
2633 /**
2634 * Returns the type of match that this class represents.
2635 *
2636 * @return {String}
2637 */
2638 getType : function() {
2639 return 'hashtag';
2640 },
2641
2642
2643 /**
2644 * Returns the configured {@link #serviceName} to point the Hashtag to.
2645 * Ex: 'facebook', 'twitter'.
2646 *
2647 * @return {String}
2648 */
2649 getServiceName : function() {
2650 return this.serviceName;
2651 },
2652
2653
2654 /**
2655 * Returns the matched hashtag, without the '#' character.
2656 *
2657 * @return {String}
2658 */
2659 getHashtag : function() {
2660 return this.hashtag;
2661 },
2662
2663
2664 /**
2665 * Returns the anchor href that should be generated for the match.
2666 *
2667 * @return {String}
2668 */
2669 getAnchorHref : function() {
2670 var serviceName = this.serviceName,
2671 hashtag = this.hashtag;
2672
2673 switch( serviceName ) {
2674 case 'twitter' :
2675 return 'https://twitter.com/hashtag/' + hashtag;
2676 case 'facebook' :
2677 return 'https://www.facebook.com/hashtag/' + hashtag;
2678 case 'instagram' :
2679 return 'https://instagram.com/explore/tags/' + hashtag;
2680
2681 default : // Shouldn't happen because Autolinker's constructor should block any invalid values, but just in case.
2682 throw new Error( 'Unknown service name to point hashtag to: ', serviceName );
2683 }
2684 },
2685
2686
2687 /**
2688 * Returns the anchor text that should be generated for the match.
2689 *
2690 * @return {String}
2691 */
2692 getAnchorText : function() {
2693 return '#' + this.hashtag;
2694 }
2695
2696 } );
2697
2698 /*global Autolinker */
2699 /**
2700 * @class Autolinker.match.Phone
2701 * @extends Autolinker.match.Match
2702 *
2703 * Represents a Phone number match found in an input string which should be
2704 * Autolinked.
2705 *
2706 * See this class's superclass ({@link Autolinker.match.Match}) for more
2707 * details.
2708 */
2709 Autolinker.match.Phone = Autolinker.Util.extend( Autolinker.match.Match, {
2710
2711 /**
2712 * @protected
2713 * @property {String} number (required)
2714 *
2715 * The phone number that was matched, without any delimiter characters.
2716 *
2717 * Note: This is a string to allow for prefixed 0's.
2718 */
2719
2720 /**
2721 * @protected
2722 * @property {Boolean} plusSign (required)
2723 *
2724 * `true` if the matched phone number started with a '+' sign. We'll include
2725 * it in the `tel:` URL if so, as this is needed for international numbers.
2726 *
2727 * Ex: '+1 (123) 456 7879'
2728 */
2729
2730
2731 /**
2732 * @constructor
2733 * @param {Object} cfg The configuration properties for the Match
2734 * instance, specified in an Object (map).
2735 */
2736 constructor : function( cfg ) {
2737 Autolinker.match.Match.prototype.constructor.call( this, cfg );
2738
2739 if( !cfg.number ) throw new Error( '`number` cfg required' );
2740 if( cfg.plusSign == null ) throw new Error( '`plusSign` cfg required' );
2741
2742 this.number = cfg.number;
2743 this.plusSign = cfg.plusSign;
2744 },
2745
2746
2747 /**
2748 * Returns a string name for the type of match that this class represents.
2749 *
2750 * @return {String}
2751 */
2752 getType : function() {
2753 return 'phone';
2754 },
2755
2756
2757 /**
2758 * Returns the phone number that was matched as a string, without any
2759 * delimiter characters.
2760 *
2761 * Note: This is a string to allow for prefixed 0's.
2762 *
2763 * @return {String}
2764 */
2765 getNumber: function() {
2766 return this.number;
2767 },
2768
2769
2770 /**
2771 * Returns the anchor href that should be generated for the match.
2772 *
2773 * @return {String}
2774 */
2775 getAnchorHref : function() {
2776 return 'tel:' + ( this.plusSign ? '+' : '' ) + this.number;
2777 },
2778
2779
2780 /**
2781 * Returns the anchor text that should be generated for the match.
2782 *
2783 * @return {String}
2784 */
2785 getAnchorText : function() {
2786 return this.matchedText;
2787 }
2788
2789 } );
2790
2791 /*global Autolinker */
2792 /**
2793 * @class Autolinker.match.Mention
2794 * @extends Autolinker.match.Match
2795 *
2796 * Represents a Mention match found in an input string which should be Autolinked.
2797 *
2798 * See this class's superclass ({@link Autolinker.match.Match}) for more details.
2799 */
2800 Autolinker.match.Mention = Autolinker.Util.extend( Autolinker.match.Match, {
2801
2802 /**
2803 * @cfg {String} serviceName
2804 *
2805 * The service to point mention matches to. See {@link Autolinker#mention}
2806 * for available values.
2807 */
2808
2809 /**
2810 * @cfg {String} mention (required)
2811 *
2812 * The Mention that was matched, without the '@' character.
2813 */
2814
2815
2816 /**
2817 * @constructor
2818 * @param {Object} cfg The configuration properties for the Match
2819 * instance, specified in an Object (map).
2820 */
2821 constructor : function( cfg ) {
2822 Autolinker.match.Match.prototype.constructor.call( this, cfg );
2823
2824 if( !cfg.serviceName ) throw new Error( '`serviceName` cfg required' );
2825 if( !cfg.mention ) throw new Error( '`mention` cfg required' );
2826
2827 this.mention = cfg.mention;
2828 this.serviceName = cfg.serviceName;
2829 },
2830
2831
2832 /**
2833 * Returns the type of match that this class represents.
2834 *
2835 * @return {String}
2836 */
2837 getType : function() {
2838 return 'mention';
2839 },
2840
2841
2842 /**
2843 * Returns the mention, without the '@' character.
2844 *
2845 * @return {String}
2846 */
2847 getMention : function() {
2848 return this.mention;
2849 },
2850
2851
2852 /**
2853 * Returns the configured {@link #serviceName} to point the mention to.
2854 * Ex: 'instagram', 'twitter', 'soundcloud'.
2855 *
2856 * @return {String}
2857 */
2858 getServiceName : function() {
2859 return this.serviceName;
2860 },
2861
2862
2863 /**
2864 * Returns the anchor href that should be generated for the match.
2865 *
2866 * @return {String}
2867 */
2868 getAnchorHref : function() {
2869 switch( this.serviceName ) {
2870 case 'twitter' :
2871 return 'https://twitter.com/' + this.mention;
2872 case 'instagram' :
2873 return 'https://instagram.com/' + this.mention;
2874 case 'soundcloud' :
2875 return 'https://soundcloud.com/' + this.mention;
2876
2877 default : // Shouldn't happen because Autolinker's constructor should block any invalid values, but just in case.
2878 throw new Error( 'Unknown service name to point mention to: ', this.serviceName );
2879 }
2880 },
2881
2882
2883 /**
2884 * Returns the anchor text that should be generated for the match.
2885 *
2886 * @return {String}
2887 */
2888 getAnchorText : function() {
2889 return '@' + this.mention;
2890 },
2891
2892
2893 /**
2894 * Returns the CSS class suffixes that should be used on a tag built with
2895 * the match. See {@link Autolinker.match.Match#getCssClassSuffixes} for
2896 * details.
2897 *
2898 * @return {String[]}
2899 */
2900 getCssClassSuffixes : function() {
2901 var cssClassSuffixes = Autolinker.match.Match.prototype.getCssClassSuffixes.call( this ),
2902 serviceName = this.getServiceName();
2903
2904 if( serviceName ) {
2905 cssClassSuffixes.push( serviceName );
2906 }
2907 return cssClassSuffixes;
2908 }
2909
2910 } );
2911
2912 /*global Autolinker */
2913 /**
2914 * @class Autolinker.match.Url
2915 * @extends Autolinker.match.Match
2916 *
2917 * Represents a Url match found in an input string which should be Autolinked.
2918 *
2919 * See this class's superclass ({@link Autolinker.match.Match}) for more details.
2920 */
2921 Autolinker.match.Url = Autolinker.Util.extend( Autolinker.match.Match, {
2922
2923 /**
2924 * @cfg {String} url (required)
2925 *
2926 * The url that was matched.
2927 */
2928
2929 /**
2930 * @cfg {"scheme"/"www"/"tld"} urlMatchType (required)
2931 *
2932 * The type of URL match that this class represents. This helps to determine
2933 * if the match was made in the original text with a prefixed scheme (ex:
2934 * 'http://www.google.com'), a prefixed 'www' (ex: 'www.google.com'), or
2935 * was matched by a known top-level domain (ex: 'google.com').
2936 */
2937
2938 /**
2939 * @cfg {Boolean} protocolUrlMatch (required)
2940 *
2941 * `true` if the URL is a match which already has a protocol (i.e.
2942 * 'http://'), `false` if the match was from a 'www' or known TLD match.
2943 */
2944
2945 /**
2946 * @cfg {Boolean} protocolRelativeMatch (required)
2947 *
2948 * `true` if the URL is a protocol-relative match. A protocol-relative match
2949 * is a URL that starts with '//', and will be either http:// or https://
2950 * based on the protocol that the site is loaded under.
2951 */
2952
2953 /**
2954 * @cfg {Object} stripPrefix (required)
2955 *
2956 * The Object form of {@link Autolinker#cfg-stripPrefix}.
2957 */
2958
2959 /**
2960 * @cfg {Boolean} stripTrailingSlash (required)
2961 * @inheritdoc Autolinker#cfg-stripTrailingSlash
2962 */
2963
2964 /**
2965 * @cfg {Boolean} decodePercentEncoding (required)
2966 * @inheritdoc Autolinker#cfg-decodePercentEncoding
2967 */
2968
2969 /**
2970 * @constructor
2971 * @param {Object} cfg The configuration properties for the Match
2972 * instance, specified in an Object (map).
2973 */
2974 constructor : function( cfg ) {
2975 Autolinker.match.Match.prototype.constructor.call( this, cfg );
2976
2977 if( cfg.urlMatchType !== 'scheme' && cfg.urlMatchType !== 'www' && cfg.urlMatchType !== 'tld' ) throw new Error( '`urlMatchType` cfg must be one of: "scheme", "www", or "tld"' );
2978 if( !cfg.url ) throw new Error( '`url` cfg required' );
2979 if( cfg.protocolUrlMatch == null ) throw new Error( '`protocolUrlMatch` cfg required' );
2980 if( cfg.protocolRelativeMatch == null ) throw new Error( '`protocolRelativeMatch` cfg required' );
2981 if( cfg.stripPrefix == null ) throw new Error( '`stripPrefix` cfg required' );
2982 if( cfg.stripTrailingSlash == null ) throw new Error( '`stripTrailingSlash` cfg required' );
2983 if( cfg.decodePercentEncoding == null ) throw new Error( '`decodePercentEncoding` cfg required' );
2984
2985 this.urlMatchType = cfg.urlMatchType;
2986 this.url = cfg.url;
2987 this.protocolUrlMatch = cfg.protocolUrlMatch;
2988 this.protocolRelativeMatch = cfg.protocolRelativeMatch;
2989 this.stripPrefix = cfg.stripPrefix;
2990 this.stripTrailingSlash = cfg.stripTrailingSlash;
2991 this.decodePercentEncoding = cfg.decodePercentEncoding;
2992 },
2993
2994
2995 /**
2996 * @private
2997 * @property {RegExp} schemePrefixRegex
2998 *
2999 * A regular expression used to remove the 'http://' or 'https://' from
3000 * URLs.
3001 */
3002 schemePrefixRegex: /^(https?:\/\/)?/i,
3003
3004 /**
3005 * @private
3006 * @property {RegExp} wwwPrefixRegex
3007 *
3008 * A regular expression used to remove the 'www.' from URLs.
3009 */
3010 wwwPrefixRegex: /^(https?:\/\/)?(www\.)?/i,
3011
3012 /**
3013 * @private
3014 * @property {RegExp} protocolRelativeRegex
3015 *
3016 * The regular expression used to remove the protocol-relative '//' from the {@link #url} string, for purposes
3017 * of {@link #getAnchorText}. A protocol-relative URL is, for example, "//yahoo.com"
3018 */
3019 protocolRelativeRegex : /^\/\//,
3020
3021 /**
3022 * @private
3023 * @property {Boolean} protocolPrepended
3024 *
3025 * Will be set to `true` if the 'http://' protocol has been prepended to the {@link #url} (because the
3026 * {@link #url} did not have a protocol)
3027 */
3028 protocolPrepended : false,
3029
3030
3031 /**
3032 * Returns a string name for the type of match that this class represents.
3033 *
3034 * @return {String}
3035 */
3036 getType : function() {
3037 return 'url';
3038 },
3039
3040
3041 /**
3042 * Returns a string name for the type of URL match that this class
3043 * represents.
3044 *
3045 * This helps to determine if the match was made in the original text with a
3046 * prefixed scheme (ex: 'http://www.google.com'), a prefixed 'www' (ex:
3047 * 'www.google.com'), or was matched by a known top-level domain (ex:
3048 * 'google.com').
3049 *
3050 * @return {"scheme"/"www"/"tld"}
3051 */
3052 getUrlMatchType : function() {
3053 return this.urlMatchType;
3054 },
3055
3056
3057 /**
3058 * Returns the url that was matched, assuming the protocol to be 'http://' if the original
3059 * match was missing a protocol.
3060 *
3061 * @return {String}
3062 */
3063 getUrl : function() {
3064 var url = this.url;
3065
3066 // if the url string doesn't begin with a protocol, assume 'http://'
3067 if( !this.protocolRelativeMatch && !this.protocolUrlMatch && !this.protocolPrepended ) {
3068 url = this.url = 'http://' + url;
3069
3070 this.protocolPrepended = true;
3071 }
3072
3073 return url;
3074 },
3075
3076
3077 /**
3078 * Returns the anchor href that should be generated for the match.
3079 *
3080 * @return {String}
3081 */
3082 getAnchorHref : function() {
3083 var url = this.getUrl();
3084
3085 return url.replace( /&amp;/g, '&' ); // any &amp;'s in the URL should be converted back to '&' if they were displayed as &amp; in the source html
3086 },
3087
3088
3089 /**
3090 * Returns the anchor text that should be generated for the match.
3091 *
3092 * @return {String}
3093 */
3094 getAnchorText : function() {
3095 var anchorText = this.getMatchedText();
3096
3097 if( this.protocolRelativeMatch ) {
3098 // Strip off any protocol-relative '//' from the anchor text
3099 anchorText = this.stripProtocolRelativePrefix( anchorText );
3100 }
3101 if( this.stripPrefix.scheme ) {
3102 anchorText = this.stripSchemePrefix( anchorText );
3103 }
3104 if( this.stripPrefix.www ) {
3105 anchorText = this.stripWwwPrefix( anchorText );
3106 }
3107 if( this.stripTrailingSlash ) {
3108 anchorText = this.removeTrailingSlash( anchorText ); // remove trailing slash, if there is one
3109 }
3110 if( this.decodePercentEncoding ) {
3111 anchorText = this.removePercentEncoding( anchorText);
3112 }
3113
3114 return anchorText;
3115 },
3116
3117
3118 // ---------------------------------------
3119
3120 // Utility Functionality
3121
3122 /**
3123 * Strips the scheme prefix (such as "http://" or "https://") from the given
3124 * `url`.
3125 *
3126 * @private
3127 * @param {String} url The text of the anchor that is being generated, for
3128 * which to strip off the url scheme.
3129 * @return {String} The `url`, with the scheme stripped.
3130 */
3131 stripSchemePrefix : function( url ) {
3132 return url.replace( this.schemePrefixRegex, '' );
3133 },
3134
3135
3136 /**
3137 * Strips the 'www' prefix from the given `url`.
3138 *
3139 * @private
3140 * @param {String} url The text of the anchor that is being generated, for
3141 * which to strip off the 'www' if it exists.
3142 * @return {String} The `url`, with the 'www' stripped.
3143 */
3144 stripWwwPrefix : function( url ) {
3145 return url.replace( this.wwwPrefixRegex, '$1' ); // leave any scheme ($1), it one exists
3146 },
3147
3148
3149 /**
3150 * Strips any protocol-relative '//' from the anchor text.
3151 *
3152 * @private
3153 * @param {String} text The text of the anchor that is being generated, for which to strip off the
3154 * protocol-relative prefix (such as stripping off "//")
3155 * @return {String} The `anchorText`, with the protocol-relative prefix stripped.
3156 */
3157 stripProtocolRelativePrefix : function( text ) {
3158 return text.replace( this.protocolRelativeRegex, '' );
3159 },
3160
3161
3162 /**
3163 * Removes any trailing slash from the given `anchorText`, in preparation for the text to be displayed.
3164 *
3165 * @private
3166 * @param {String} anchorText The text of the anchor that is being generated, for which to remove any trailing
3167 * slash ('/') that may exist.
3168 * @return {String} The `anchorText`, with the trailing slash removed.
3169 */
3170 removeTrailingSlash : function( anchorText ) {
3171 if( anchorText.charAt( anchorText.length - 1 ) === '/' ) {
3172 anchorText = anchorText.slice( 0, -1 );
3173 }
3174 return anchorText;
3175 },
3176
3177 /**
3178 * Decodes percent-encoded characters from the given `anchorText`, in preparation for the text to be displayed.
3179 *
3180 * @private
3181 * @param {String} anchorText The text of the anchor that is being generated, for which to decode any percent-encoded characters.
3182 * @return {String} The `anchorText`, with the percent-encoded characters decoded.
3183 */
3184 removePercentEncoding : function( anchorText ) {
3185 try {
3186 return decodeURIComponent( anchorText
3187 .replace( /%22/gi, '&quot;' )
3188 .replace( /%26/gi, '&amp;' )
3189 .replace( /%27/gi, '&#39;')
3190 .replace( /%3C/gi, '&lt;' )
3191 .replace( /%3E/gi, '&gt;' )
3192 );
3193 } catch (e) {
3194 // Invalid escape sequence.
3195 return anchorText;
3196 }
3197 }
3198
3199 } );
3200 // NOTE: THIS IS A GENERATED FILE
3201 // To update with the latest TLD list, run `gulp update-tld-list`
3202
3203 /*global Autolinker */
3204 Autolinker.tldRegex = /(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|northwesternmutual|travelersinsurance|vermögensberatung|xn--3oq18vl8pn36a|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|vermögensberater|xn--fzys8d69uvgm|xn--mgba7c0bbn0a|xn--xkc2al3hye2a|americanexpress|kerryproperties|sandvikcoromant|xn--i1b6b1a6a2e|xn--kcrx77d1x4a|xn--lgbbat1ad8j|xn--mgba3a4f16a|xn--mgbc0a9azcg|xn--nqv7fs00ema|afamilycompany|americanfamily|bananarepublic|cancerresearch|cookingchannel|kerrylogistics|weatherchannel|xn--54b7fta0cc|xn--6qq986b3xl|xn--80aqecdr1a|xn--b4w605ferd|xn--fiq228c5hs|xn--jlq61u9w7b|xn--mgba3a3ejt|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--mgbb9fbpob|xn--mgbbh1a71e|xn--mgbca7dzdo|xn--mgbi4ecexp|xn--mgbx4cd0ab|international|lifeinsurance|orientexpress|spreadbetting|travelchannel|wolterskluwer|xn--eckvdtc9d|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--tiq49xqyj|xn--yfro4i67o|xn--ygbi2ammx|construction|lplfinancial|pamperedchef|scholarships|versicherung|xn--3e0b707e|xn--80adxhks|xn--80asehdb|xn--8y0a063a|xn--gckr3f0f|xn--mgb9awbf|xn--mgbab2bd|xn--mgbpl2fh|xn--mgbt3dhd|xn--mk1bu44c|xn--ngbc5azd|xn--ngbe9e0a|xn--ogbpf8fl|xn--qcka1pmc|accountants|barclaycard|blackfriday|blockbuster|bridgestone|calvinklein|contractors|creditunion|engineering|enterprises|foodnetwork|investments|kerryhotels|lamborghini|motorcycles|olayangroup|photography|playstation|productions|progressive|redumbrella|rightathome|williamhill|xn--11b4c3d|xn--1ck2e1b|xn--1qqw23a|xn--3bst00m|xn--3ds443g|xn--42c2d9a|xn--45brj9c|xn--55qw42g|xn--6frz82g|xn--80ao21a|xn--9krt00a|xn--cck2b3b|xn--czr694b|xn--d1acj3b|xn--efvy88h|xn--estv75g|xn--fct429k|xn--fjq720a|xn--flw351e|xn--g2xx48c|xn--gecrj9c|xn--gk3at1e|xn--h2brj9c|xn--hxt814e|xn--imr513n|xn--j6w193g|xn--jvr189m|xn--kprw13d|xn--kpry57d|xn--kpu716f|xn--mgbtx2b|xn--mix891f|xn--nyqy26a|xn--pbt977c|xn--pgbs0dh|xn--q9jyb4c|xn--rhqv96g|xn--rovu88b|xn--s9brj9c|xn--ses554g|xn--t60b56a|xn--vuq861b|xn--w4rs40l|xn--xhq521b|xn--zfr164b|சிங்கப்பூர்|accountant|apartments|associates|basketball|bnpparibas|boehringer|capitalone|consulting|creditcard|cuisinella|eurovision|extraspace|foundation|healthcare|immobilien|industries|management|mitsubishi|nationwide|newholland|nextdirect|onyourside|properties|protection|prudential|realestate|republican|restaurant|schaeffler|swiftcover|tatamotors|technology|telefonica|university|vistaprint|vlaanderen|volkswagen|xn--30rr7y|xn--3pxu8k|xn--45q11c|xn--4gbrim|xn--55qx5d|xn--5tzm5g|xn--80aswg|xn--90a3ac|xn--9dbq2a|xn--9et52u|xn--c2br7g|xn--cg4bki|xn--czrs0t|xn--czru2d|xn--fiq64b|xn--fiqs8s|xn--fiqz9s|xn--io0a7i|xn--kput3i|xn--mxtq1m|xn--o3cw4h|xn--pssy2u|xn--unup4y|xn--wgbh1c|xn--wgbl6a|xn--y9a3aq|accenture|alfaromeo|allfinanz|amsterdam|analytics|aquarelle|barcelona|bloomberg|christmas|community|directory|education|equipment|fairwinds|financial|firestone|fresenius|frontdoor|fujixerox|furniture|goldpoint|goodhands|hisamitsu|homedepot|homegoods|homesense|honeywell|institute|insurance|kuokgroup|ladbrokes|lancaster|landrover|lifestyle|marketing|marshalls|mcdonalds|melbourne|microsoft|montblanc|panasonic|passagens|pramerica|richardli|scjohnson|shangrila|solutions|statebank|statefarm|stockholm|travelers|vacations|xn--90ais|xn--c1avg|xn--d1alf|xn--e1a4c|xn--fhbei|xn--j1aef|xn--j1amh|xn--l1acc|xn--nqv7f|xn--p1acf|xn--tckwe|xn--vhquv|yodobashi|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|budapest|builders|business|capetown|catering|catholic|chrysler|cipriani|cityeats|cleaning|clinique|clothing|commbank|computer|delivery|deloitte|democrat|diamonds|discount|discover|download|engineer|ericsson|esurance|everbank|exchange|feedback|fidelity|firmdale|football|frontier|goodyear|grainger|graphics|guardian|hdfcbank|helsinki|holdings|hospital|infiniti|ipiranga|istanbul|jpmorgan|lighting|lundbeck|marriott|maserati|mckinsey|memorial|mortgage|movistar|observer|partners|pharmacy|pictures|plumbing|property|redstone|reliance|saarland|samsclub|security|services|shopping|showtime|softbank|software|stcgroup|supplies|symantec|telecity|training|uconnect|vanguard|ventures|verisign|woodside|xn--90ae|xn--node|xn--p1ai|xn--qxam|yokohama|السعودية|abogado|academy|agakhan|alibaba|android|athleta|auction|audible|auspost|avianca|banamex|bauhaus|bentley|bestbuy|booking|brother|bugatti|capital|caravan|careers|cartier|channel|chintai|citadel|clubmed|college|cologne|comcast|company|compare|contact|cooking|corsica|country|coupons|courses|cricket|cruises|dentist|digital|domains|exposed|express|farmers|fashion|ferrari|ferrero|finance|fishing|fitness|flights|florist|flowers|forsale|frogans|fujitsu|gallery|genting|godaddy|guitars|hamburg|hangout|hitachi|holiday|hosting|hoteles|hotmail|hyundai|iselect|ismaili|jewelry|juniper|kitchen|komatsu|lacaixa|lancome|lanxess|lasalle|latrobe|leclerc|liaison|limited|lincoln|markets|metlife|monster|netbank|netflix|network|neustar|okinawa|oldnavy|organic|origins|panerai|philips|pioneer|politie|realtor|recipes|rentals|reviews|rexroth|samsung|sandvik|schmidt|schwarz|science|shiksha|shriram|singles|spiegel|staples|starhub|statoil|storage|support|surgery|systems|temasek|theater|theatre|tickets|tiffany|toshiba|trading|walmart|wanggou|watches|weather|website|wedding|whoswho|windows|winners|xfinity|yamaxun|youtube|zuerich|католик|الجزائر|العليان|پاکستان|كاثوليك|موبايلي|இந்தியா|abarth|abbott|abbvie|active|africa|agency|airbus|airtel|alipay|alsace|alstom|anquan|aramco|author|bayern|beauty|berlin|bharti|blanco|bostik|boston|broker|camera|career|caseih|casino|center|chanel|chrome|church|circle|claims|clinic|coffee|comsec|condos|coupon|credit|cruise|dating|datsun|dealer|degree|dental|design|direct|doctor|dunlop|dupont|durban|emerck|energy|estate|events|expert|family|flickr|futbol|gallup|garden|george|giving|global|google|gratis|health|hermes|hiphop|hockey|hughes|imamat|insure|intuit|jaguar|joburg|juegos|kaufen|kinder|kindle|kosher|lancia|latino|lawyer|lefrak|living|locker|london|luxury|madrid|maison|makeup|market|mattel|mobile|mobily|monash|mormon|moscow|museum|mutual|nagoya|natura|nissan|nissay|norton|nowruz|office|olayan|online|oracle|orange|otsuka|pfizer|photos|physio|piaget|pictet|quebec|racing|realty|reisen|repair|report|review|rocher|rogers|ryukyu|safety|sakura|sanofi|school|schule|secure|select|shouji|soccer|social|stream|studio|supply|suzuki|swatch|sydney|taipei|taobao|target|tattoo|tennis|tienda|tjmaxx|tkmaxx|toyota|travel|unicom|viajes|viking|villas|virgin|vision|voting|voyage|vuelos|walter|warman|webcam|xihuan|xperia|yachts|yandex|zappos|москва|онлайн|ابوظبي|ارامكو|الاردن|المغرب|امارات|فلسطين|مليسيا|இலங்கை|ファッション|actor|adult|aetna|amfam|amica|apple|archi|audio|autos|azure|baidu|beats|bible|bingo|black|boats|boots|bosch|build|canon|cards|chase|cheap|chloe|cisco|citic|click|cloud|coach|codes|crown|cymru|dabur|dance|deals|delta|dodge|drive|dubai|earth|edeka|email|epost|epson|faith|fedex|final|forex|forum|gallo|games|gifts|gives|glade|glass|globo|gmail|green|gripe|group|gucci|guide|homes|honda|horse|house|hyatt|ikano|intel|irish|iveco|jetzt|koeln|kyoto|lamer|lease|legal|lexus|lilly|linde|lipsy|lixil|loans|locus|lotte|lotto|lupin|macys|mango|media|miami|money|mopar|movie|nadex|nexus|nikon|ninja|nokia|nowtv|omega|osaka|paris|parts|party|phone|photo|pizza|place|poker|praxi|press|prime|promo|quest|radio|rehab|reise|ricoh|rocks|rodeo|salon|sener|seven|sharp|shell|shoes|skype|sling|smart|smile|solar|space|stada|store|study|style|sucks|swiss|tatar|tires|tirol|tmall|today|tokyo|tools|toray|total|tours|trade|trust|tunes|tushu|ubank|vegas|video|vista|vodka|volvo|wales|watch|weber|weibo|works|world|xerox|yahoo|zippo|ایران|بازار|بھارت|سودان|سورية|همراه|संगठन|বাংলা|భారత్|嘉里大酒店|aarp|able|adac|aero|aigo|akdn|ally|amex|army|arpa|arte|asda|asia|audi|auto|baby|band|bank|bbva|beer|best|bike|bing|blog|blue|bofa|bond|book|buzz|cafe|call|camp|care|cars|casa|case|cash|cbre|cern|chat|citi|city|club|cool|coop|cyou|data|date|dclk|deal|dell|desi|diet|dish|docs|doha|duck|duns|dvag|erni|fage|fail|fans|farm|fast|fiat|fido|film|fire|fish|flir|food|ford|free|fund|game|gbiz|gent|ggee|gift|gmbh|gold|golf|goog|guge|guru|hair|haus|hdfc|help|here|hgtv|host|hsbc|icbc|ieee|imdb|immo|info|itau|java|jeep|jobs|jprs|kddi|kiwi|kpmg|kred|land|lego|lgbt|lidl|life|like|limo|link|live|loan|loft|love|ltda|luxe|maif|meet|meme|menu|mini|mint|mobi|moda|moto|mtpc|name|navy|news|next|nico|nike|ollo|open|page|pars|pccw|pics|ping|pink|play|plus|pohl|porn|post|prod|prof|qpon|raid|read|reit|rent|rest|rich|rmit|room|rsvp|ruhr|safe|sale|sapo|sarl|save|saxo|scor|scot|seat|seek|sexy|shaw|shia|shop|show|silk|sina|site|skin|sncf|sohu|song|sony|spot|star|surf|talk|taxi|team|tech|teva|tiaa|tips|town|toys|tube|vana|visa|viva|vivo|vote|voto|wang|weir|wien|wiki|wine|work|xbox|yoga|zara|zero|zone|дети|сайт|بيتك|تونس|شبكة|عراق|عمان|موقع|भारत|ভারত|ਭਾਰਤ|ભારત|ලංකා|グーグル|クラウド|ポイント|大众汽车|组织机构|電訊盈科|香格里拉|aaa|abb|abc|aco|ads|aeg|afl|aig|anz|aol|app|art|aws|axa|bar|bbc|bbt|bcg|bcn|bet|bid|bio|biz|bms|bmw|bnl|bom|boo|bot|box|buy|bzh|cab|cal|cam|car|cat|cba|cbn|cbs|ceb|ceo|cfa|cfd|com|crs|csc|dad|day|dds|dev|dhl|diy|dnp|dog|dot|dtv|dvr|eat|eco|edu|esq|eus|fan|fit|fly|foo|fox|frl|ftr|fun|fyi|gal|gap|gdn|gea|gle|gmo|gmx|goo|gop|got|gov|hbo|hiv|hkt|hot|how|htc|ibm|ice|icu|ifm|ing|ink|int|ist|itv|iwc|jcb|jcp|jio|jlc|jll|jmp|jnj|jot|joy|kfh|kia|kim|kpn|krd|lat|law|lds|lol|lpl|ltd|man|mba|mcd|med|men|meo|mil|mit|mlb|mls|mma|moe|moi|mom|mov|msd|mtn|mtr|nab|nba|nec|net|new|nfl|ngo|nhk|now|nra|nrw|ntt|nyc|obi|off|one|ong|onl|ooo|org|ott|ovh|pay|pet|pid|pin|pnc|pro|pru|pub|pwc|qvc|red|ren|ril|rio|rip|run|rwe|sap|sas|sbi|sbs|sca|scb|ses|sew|sex|sfr|ski|sky|soy|srl|srt|stc|tab|tax|tci|tdk|tel|thd|tjx|top|trv|tui|tvs|ubs|uno|uol|ups|vet|vig|vin|vip|wed|win|wme|wow|wtc|wtf|xin|xxx|xyz|you|yun|zip|бел|ком|қаз|мкд|мон|орг|рус|срб|укр|հայ|קום|قطر|كوم|مصر|कॉम|नेट|คอม|ไทย|ストア|セール|みんな|中文网|天主教|我爱你|新加坡|淡马锡|诺基亚|飞利浦|ac|ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw|ελ|бг|ею|рф|გე|닷넷|닷컴|삼성|한국|コム|世界|中信|中国|中國|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|嘉里|在线|大拿|娱乐|家電|工行|广东|微博|慈善|手机|手表|政务|政府|新闻|时尚|書籍|机构|游戏|澳門|点看|珠宝|移动|网址|网店|网站|网络|联通|谷歌|购物|通販|集团|食品|餐厅|香港)/;
3205
3206 /*global Autolinker */
3207 /**
3208 * @abstract
3209 * @class Autolinker.matcher.Matcher
3210 *
3211 * An abstract class and interface for individual matchers to find matches in
3212 * an input string with linkified versions of them.
3213 *
3214 * Note that Matchers do not take HTML into account - they must be fed the text
3215 * nodes of any HTML string, which is handled by {@link Autolinker#parse}.
3216 */
3217 Autolinker.matcher.Matcher = Autolinker.Util.extend( Object, {
3218
3219 /**
3220 * @cfg {Autolinker.AnchorTagBuilder} tagBuilder (required)
3221 *
3222 * Reference to the AnchorTagBuilder instance to use to generate HTML tags
3223 * for {@link Autolinker.match.Match Matches}.
3224 */
3225
3226
3227 /**
3228 * @constructor
3229 * @param {Object} cfg The configuration properties for the Matcher
3230 * instance, specified in an Object (map).
3231 */
3232 constructor : function( cfg ) {
3233 if( !cfg.tagBuilder ) throw new Error( '`tagBuilder` cfg required' );
3234
3235 this.tagBuilder = cfg.tagBuilder;
3236 },
3237
3238
3239 /**
3240 * Parses the input `text` and returns the array of {@link Autolinker.match.Match Matches}
3241 * for the matcher.
3242 *
3243 * @abstract
3244 * @param {String} text The text to scan and replace matches in.
3245 * @return {Autolinker.match.Match[]}
3246 */
3247 parseMatches : Autolinker.Util.abstractMethod
3248
3249 } );
3250 /*global Autolinker */
3251 /**
3252 * @class Autolinker.matcher.Email
3253 * @extends Autolinker.matcher.Matcher
3254 *
3255 * Matcher to find email matches in an input string.
3256 *
3257 * See this class's superclass ({@link Autolinker.matcher.Matcher}) for more details.
3258 */
3259 Autolinker.matcher.Email = Autolinker.Util.extend( Autolinker.matcher.Matcher, {
3260
3261 /**
3262 * The regular expression to match email addresses. Example match:
3263 *
3264 * [email protected]
3265 *
3266 * @private
3267 * @property {RegExp} matcherRegex
3268 */
3269 matcherRegex : (function() {
3270 var alphaNumericChars = Autolinker.RegexLib.alphaNumericCharsStr,
3271 specialCharacters = '!#$%&\'*+\\-\\/=?^_`{|}~',
3272 restrictedSpecialCharacters = '\\s"(),:;<>@\\[\\]',
3273 validCharacters = alphaNumericChars + specialCharacters,
3274 validRestrictedCharacters = validCharacters + restrictedSpecialCharacters,
3275 emailRegex = new RegExp( '(?:[' + validCharacters + '](?:[' + validCharacters + ']|\\.(?!\\.|@))*|\\"[' + validRestrictedCharacters + '.]+\\")@'),
3276 getDomainNameStr = Autolinker.RegexLib.getDomainNameStr,
3277 tldRegex = Autolinker.tldRegex; // match our known top level domains (TLDs)
3278
3279 return new RegExp( [
3280 emailRegex.source,
3281 getDomainNameStr(1),
3282 '\\.', tldRegex.source // '.com', '.net', etc
3283 ].join( "" ), 'gi' );
3284 } )(),
3285
3286
3287 /**
3288 * @inheritdoc
3289 */
3290 parseMatches : function( text ) {
3291 var matcherRegex = this.matcherRegex,
3292 tagBuilder = this.tagBuilder,
3293 matches = [],
3294 match;
3295
3296 while( ( match = matcherRegex.exec( text ) ) !== null ) {
3297 var matchedText = match[ 0 ];
3298
3299 matches.push( new Autolinker.match.Email( {
3300 tagBuilder : tagBuilder,
3301 matchedText : matchedText,
3302 offset : match.index,
3303 email : matchedText
3304 } ) );
3305 }
3306
3307 return matches;
3308 }
3309
3310 } );
3311
3312 /*global Autolinker */
3313 /**
3314 * @class Autolinker.matcher.Hashtag
3315 * @extends Autolinker.matcher.Matcher
3316 *
3317 * Matcher to find Hashtag matches in an input string.
3318 */
3319 Autolinker.matcher.Hashtag = Autolinker.Util.extend( Autolinker.matcher.Matcher, {
3320
3321 /**
3322 * @cfg {String} serviceName
3323 *
3324 * The service to point hashtag matches to. See {@link Autolinker#hashtag}
3325 * for available values.
3326 */
3327
3328
3329 /**
3330 * The regular expression to match Hashtags. Example match:
3331 *
3332 * #asdf
3333 *
3334 * @private
3335 * @property {RegExp} matcherRegex
3336 */
3337 matcherRegex : new RegExp( '#[_' + Autolinker.RegexLib.alphaNumericCharsStr + ']{1,139}', 'g' ),
3338
3339 /**
3340 * The regular expression to use to check the character before a username match to
3341 * make sure we didn't accidentally match an email address.
3342 *
3343 * For example, the string "[email protected]" should not match "@asdf" as a username.
3344 *
3345 * @private
3346 * @property {RegExp} nonWordCharRegex
3347 */
3348 nonWordCharRegex : new RegExp( '[^' + Autolinker.RegexLib.alphaNumericCharsStr + ']' ),
3349
3350
3351 /**
3352 * @constructor
3353 * @param {Object} cfg The configuration properties for the Match instance,
3354 * specified in an Object (map).
3355 */
3356 constructor : function( cfg ) {
3357 Autolinker.matcher.Matcher.prototype.constructor.call( this, cfg );
3358
3359 this.serviceName = cfg.serviceName;
3360 },
3361
3362
3363 /**
3364 * @inheritdoc
3365 */
3366 parseMatches : function( text ) {
3367 var matcherRegex = this.matcherRegex,
3368 nonWordCharRegex = this.nonWordCharRegex,
3369 serviceName = this.serviceName,
3370 tagBuilder = this.tagBuilder,
3371 matches = [],
3372 match;
3373
3374 while( ( match = matcherRegex.exec( text ) ) !== null ) {
3375 var offset = match.index,
3376 prevChar = text.charAt( offset - 1 );
3377
3378 // If we found the match at the beginning of the string, or we found the match
3379 // and there is a whitespace char in front of it (meaning it is not a '#' char
3380 // in the middle of a word), then it is a hashtag match.
3381 if( offset === 0 || nonWordCharRegex.test( prevChar ) ) {
3382 var matchedText = match[ 0 ],
3383 hashtag = match[ 0 ].slice( 1 ); // strip off the '#' character at the beginning
3384
3385 matches.push( new Autolinker.match.Hashtag( {
3386 tagBuilder : tagBuilder,
3387 matchedText : matchedText,
3388 offset : offset,
3389 serviceName : serviceName,
3390 hashtag : hashtag
3391 } ) );
3392 }
3393 }
3394
3395 return matches;
3396 }
3397
3398 } );
3399 /*global Autolinker */
3400 /**
3401 * @class Autolinker.matcher.Phone
3402 * @extends Autolinker.matcher.Matcher
3403 *
3404 * Matcher to find Phone number matches in an input string.
3405 *
3406 * See this class's superclass ({@link Autolinker.matcher.Matcher}) for more
3407 * details.
3408 */
3409 Autolinker.matcher.Phone = Autolinker.Util.extend( Autolinker.matcher.Matcher, {
3410
3411 /**
3412 * The regular expression to match Phone numbers. Example match:
3413 *
3414 * (123) 456-7890
3415 *
3416 * This regular expression has the following capturing groups:
3417 *
3418 * 1 or 2. The prefixed '+' sign, if there is one.
3419 *
3420 * @private
3421 * @property {RegExp} matcherRegex
3422 */
3423 matcherRegex : /(?:(?:(?:(\+)?\d{1,3}[-\040.]?)?\(?\d{3}\)?[-\040.]?\d{3}[-\040.]?\d{4})|(?:(\+)(?:9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)[-\040.]?(?:\d[-\040.]?){6,12}\d+))([,;]+[0-9]+#?)*/g,
3424
3425 // ex: (123) 456-7890, 123 456 7890, 123-456-7890, +18004441234,,;,10226420346#,
3426 // +1 (800) 444 1234, 10226420346#, 1-800-444-1234,1022,64,20346#
3427
3428 /**
3429 * @inheritdoc
3430 */
3431 parseMatches: function(text) {
3432 var matcherRegex = this.matcherRegex,
3433 tagBuilder = this.tagBuilder,
3434 matches = [],
3435 match;
3436
3437 while ((match = matcherRegex.exec(text)) !== null) {
3438 // Remove non-numeric values from phone number string
3439 var matchedText = match[0],
3440 cleanNumber = matchedText.replace(/[^0-9,;#]/g, ''), // strip out non-digit characters exclude comma semicolon and #
3441 plusSign = !!(match[1] || match[2]), // match[ 1 ] or match[ 2 ] is the prefixed plus sign, if there is one
3442 before = match.index == 0 ? '' : text.substr(match.index - 1, 1),
3443 after = text.substr(match.index + matchedText.length, 1),
3444 contextClear = !before.match(/\d/) && !after.match(/\d/);
3445
3446 if (this.testMatch(match[3]) && this.testMatch(matchedText) && contextClear) {
3447 matches.push(new Autolinker.match.Phone({
3448 tagBuilder: tagBuilder,
3449 matchedText: matchedText,
3450 offset: match.index,
3451 number: cleanNumber,
3452 plusSign: plusSign
3453 }));
3454 }
3455 }
3456
3457 return matches;
3458 },
3459
3460 testMatch: function(text) {
3461 return /\D/.test(text);
3462 }
3463
3464 } );
3465
3466 /*global Autolinker */
3467 /**
3468 * @class Autolinker.matcher.Mention
3469 * @extends Autolinker.matcher.Matcher
3470 *
3471 * Matcher to find/replace username matches in an input string.
3472 */
3473 Autolinker.matcher.Mention = Autolinker.Util.extend( Autolinker.matcher.Matcher, {
3474
3475 /**
3476 * Hash of regular expression to match username handles. Example match:
3477 *
3478 * @asdf
3479 *
3480 * @private
3481 * @property {Object} matcherRegexes
3482 */
3483 matcherRegexes : {
3484 "twitter": new RegExp( '@[_' + Autolinker.RegexLib.alphaNumericCharsStr + ']{1,20}', 'g' ),
3485 "instagram": new RegExp( '@[_.' + Autolinker.RegexLib.alphaNumericCharsStr + ']{1,50}', 'g' ),
3486 "soundcloud": new RegExp( '@[_.' + Autolinker.RegexLib.alphaNumericCharsStr + "\-" + ']{1,50}', 'g' )
3487 },
3488
3489 /**
3490 * The regular expression to use to check the character before a username match to
3491 * make sure we didn't accidentally match an email address.
3492 *
3493 * For example, the string "[email protected]" should not match "@asdf" as a username.
3494 *
3495 * @private
3496 * @property {RegExp} nonWordCharRegex
3497 */
3498 nonWordCharRegex : new RegExp( '[^' + Autolinker.RegexLib.alphaNumericCharsStr + ']' ),
3499
3500
3501 /**
3502 * @constructor
3503 * @param {Object} cfg The configuration properties for the Match instance,
3504 * specified in an Object (map).
3505 */
3506 constructor : function( cfg ) {
3507 Autolinker.matcher.Matcher.prototype.constructor.call( this, cfg );
3508
3509 this.serviceName = cfg.serviceName;
3510 },
3511
3512
3513 /**
3514 * @inheritdoc
3515 */
3516 parseMatches : function( text ) {
3517 var matcherRegex = this.matcherRegexes[this.serviceName],
3518 nonWordCharRegex = this.nonWordCharRegex,
3519 serviceName = this.serviceName,
3520 tagBuilder = this.tagBuilder,
3521 matches = [],
3522 match;
3523
3524 if (!matcherRegex) {
3525 return matches;
3526 }
3527
3528 while( ( match = matcherRegex.exec( text ) ) !== null ) {
3529 var offset = match.index,
3530 prevChar = text.charAt( offset - 1 );
3531
3532 // If we found the match at the beginning of the string, or we found the match
3533 // and there is a whitespace char in front of it (meaning it is not an email
3534 // address), then it is a username match.
3535 if( offset === 0 || nonWordCharRegex.test( prevChar ) ) {
3536 var matchedText = match[ 0 ].replace(/\.+$/g, ''), // strip off trailing .
3537 mention = matchedText.slice( 1 ); // strip off the '@' character at the beginning
3538
3539 matches.push( new Autolinker.match.Mention( {
3540 tagBuilder : tagBuilder,
3541 matchedText : matchedText,
3542 offset : offset,
3543 serviceName : serviceName,
3544 mention : mention
3545 } ) );
3546 }
3547 }
3548
3549 return matches;
3550 }
3551
3552 } );
3553
3554 /*global Autolinker */
3555 /**
3556 * @class Autolinker.matcher.Url
3557 * @extends Autolinker.matcher.Matcher
3558 *
3559 * Matcher to find URL matches in an input string.
3560 *
3561 * See this class's superclass ({@link Autolinker.matcher.Matcher}) for more details.
3562 */
3563 Autolinker.matcher.Url = Autolinker.Util.extend( Autolinker.matcher.Matcher, {
3564
3565 /**
3566 * @cfg {Object} stripPrefix (required)
3567 *
3568 * The Object form of {@link Autolinker#cfg-stripPrefix}.
3569 */
3570
3571 /**
3572 * @cfg {Boolean} stripTrailingSlash (required)
3573 * @inheritdoc Autolinker#stripTrailingSlash
3574 */
3575
3576 /**
3577 * @cfg {Boolean} decodePercentEncoding (required)
3578 * @inheritdoc Autolinker#decodePercentEncoding
3579 */
3580
3581
3582 /**
3583 * @private
3584 * @property {RegExp} matcherRegex
3585 *
3586 * The regular expression to match URLs with an optional scheme, port
3587 * number, path, query string, and hash anchor.
3588 *
3589 * Example matches:
3590 *
3591 * http://google.com
3592 * www.google.com
3593 * google.com/path/to/file?q1=1&q2=2#myAnchor
3594 *
3595 *
3596 * This regular expression will have the following capturing groups:
3597 *
3598 * 1. Group that matches a scheme-prefixed URL (i.e. 'http://google.com').
3599 * This is used to match scheme URLs with just a single word, such as
3600 * 'http://localhost', where we won't double check that the domain name
3601 * has at least one dot ('.') in it.
3602 * 2. Group that matches a 'www.' prefixed URL. This is only matched if the
3603 * 'www.' text was not prefixed by a scheme (i.e.: not prefixed by
3604 * 'http://', 'ftp:', etc.)
3605 * 3. A protocol-relative ('//') match for the case of a 'www.' prefixed
3606 * URL. Will be an empty string if it is not a protocol-relative match.
3607 * We need to know the character before the '//' in order to determine
3608 * if it is a valid match or the // was in a string we don't want to
3609 * auto-link.
3610 * 4. Group that matches a known TLD (top level domain), when a scheme
3611 * or 'www.'-prefixed domain is not matched.
3612 * 5. A protocol-relative ('//') match for the case of a known TLD prefixed
3613 * URL. Will be an empty string if it is not a protocol-relative match.
3614 * See #3 for more info.
3615 */
3616 matcherRegex : (function() {
3617 var schemeRegex = /(?:[A-Za-z][-.+A-Za-z0-9]{0,63}:(?![A-Za-z][-.+A-Za-z0-9]{0,63}:\/\/)(?!\d+\/?)(?:\/\/)?)/, // match protocol, allow in format "http://" or "mailto:". However, do not match the first part of something like 'link:http://www.google.com' (i.e. don't match "link:"). Also, make sure we don't interpret 'google.com:8000' as if 'google.com' was a protocol here (i.e. ignore a trailing port number in this regex)
3618 wwwRegex = /(?:www\.)/, // starting with 'www.'
3619 getDomainNameStr = Autolinker.RegexLib.getDomainNameStr,
3620 tldRegex = Autolinker.tldRegex, // match our known top level domains (TLDs)
3621 alphaNumericCharsStr = Autolinker.RegexLib.alphaNumericCharsStr,
3622
3623 // Allow optional path, query string, and hash anchor, not ending in the following characters: "?!:,.;"
3624 // http://blog.codinghorror.com/the-problem-with-urls/
3625 urlSuffixRegex = new RegExp( '[/?#](?:[' + alphaNumericCharsStr + '\\-+&@#/%=~_()|\'$*\\[\\]?!:,.;\u2713]*[' + alphaNumericCharsStr + '\\-+&@#/%=~_()|\'$*\\[\\]\u2713])?' );
3626
3627 return new RegExp( [
3628 '(?:', // parens to cover match for scheme (optional), and domain
3629 '(', // *** Capturing group $1, for a scheme-prefixed url (ex: http://google.com)
3630 schemeRegex.source,
3631 getDomainNameStr(2),
3632 ')',
3633
3634 '|',
3635
3636 '(', // *** Capturing group $4 for a 'www.' prefixed url (ex: www.google.com)
3637 '(//)?', // *** Capturing group $5 for an optional protocol-relative URL. Must be at the beginning of the string or start with a non-word character (handled later)
3638 wwwRegex.source,
3639 getDomainNameStr(6),
3640 ')',
3641
3642 '|',
3643
3644 '(', // *** Capturing group $8, for known a TLD url (ex: google.com)
3645 '(//)?', // *** Capturing group $9 for an optional protocol-relative URL. Must be at the beginning of the string or start with a non-word character (handled later)
3646 getDomainNameStr(10) + '\\.',
3647 tldRegex.source,
3648 '(?![-' + alphaNumericCharsStr + '])', // TLD not followed by a letter, behaves like unicode-aware \b
3649 ')',
3650 ')',
3651
3652 '(?::[0-9]+)?', // port
3653
3654 '(?:' + urlSuffixRegex.source + ')?' // match for path, query string, and/or hash anchor - optional
3655 ].join( "" ), 'gi' );
3656 } )(),
3657
3658
3659 /**
3660 * A regular expression to use to check the character before a protocol-relative
3661 * URL match. We don't want to match a protocol-relative URL if it is part
3662 * of another word.
3663 *
3664 * For example, we want to match something like "Go to: //google.com",
3665 * but we don't want to match something like "abc//google.com"
3666 *
3667 * This regular expression is used to test the character before the '//'.
3668 *
3669 * @private
3670 * @type {RegExp} wordCharRegExp
3671 */
3672 wordCharRegExp : new RegExp( '[' + Autolinker.RegexLib.alphaNumericCharsStr + ']' ),
3673
3674
3675 /**
3676 * The regular expression to match opening parenthesis in a URL match.
3677 *
3678 * This is to determine if we have unbalanced parenthesis in the URL, and to
3679 * drop the final parenthesis that was matched if so.
3680 *
3681 * Ex: The text "(check out: wikipedia.com/something_(disambiguation))"
3682 * should only autolink the inner "wikipedia.com/something_(disambiguation)"
3683 * part, so if we find that we have unbalanced parenthesis, we will drop the
3684 * last one for the match.
3685 *
3686 * @private
3687 * @property {RegExp}
3688 */
3689 openParensRe : /\(/g,
3690
3691 /**
3692 * The regular expression to match closing parenthesis in a URL match. See
3693 * {@link #openParensRe} for more information.
3694 *
3695 * @private
3696 * @property {RegExp}
3697 */
3698 closeParensRe : /\)/g,
3699
3700
3701 /**
3702 * @constructor
3703 * @param {Object} cfg The configuration properties for the Match instance,
3704 * specified in an Object (map).
3705 */
3706 constructor : function( cfg ) {
3707 Autolinker.matcher.Matcher.prototype.constructor.call( this, cfg );
3708
3709 if( cfg.stripPrefix == null ) throw new Error( '`stripPrefix` cfg required' );
3710 if( cfg.stripTrailingSlash == null ) throw new Error( '`stripTrailingSlash` cfg required' );
3711
3712 this.stripPrefix = cfg.stripPrefix;
3713 this.stripTrailingSlash = cfg.stripTrailingSlash;
3714 this.decodePercentEncoding = cfg.decodePercentEncoding;
3715 },
3716
3717
3718 /**
3719 * @inheritdoc
3720 */
3721 parseMatches : function( text ) {
3722 var matcherRegex = this.matcherRegex,
3723 stripPrefix = this.stripPrefix,
3724 stripTrailingSlash = this.stripTrailingSlash,
3725 decodePercentEncoding = this.decodePercentEncoding,
3726 tagBuilder = this.tagBuilder,
3727 matches = [],
3728 match;
3729
3730 while( ( match = matcherRegex.exec( text ) ) !== null ) {
3731 var matchStr = match[ 0 ],
3732 schemeUrlMatch = match[ 1 ],
3733 wwwUrlMatch = match[ 4 ],
3734 wwwProtocolRelativeMatch = match[ 5 ],
3735 //tldUrlMatch = match[ 8 ], -- not needed at the moment
3736 tldProtocolRelativeMatch = match[ 9 ],
3737 offset = match.index,
3738 protocolRelativeMatch = wwwProtocolRelativeMatch || tldProtocolRelativeMatch,
3739 prevChar = text.charAt( offset - 1 );
3740
3741 if( !Autolinker.matcher.UrlMatchValidator.isValid( matchStr, schemeUrlMatch ) ) {
3742 continue;
3743 }
3744
3745 // If the match is preceded by an '@' character, then it is either
3746 // an email address or a username. Skip these types of matches.
3747 if( offset > 0 && prevChar === '@' ) {
3748 continue;
3749 }
3750
3751 // If it's a protocol-relative '//' match, but the character before the '//'
3752 // was a word character (i.e. a letter/number), then we found the '//' in the
3753 // middle of another word (such as "asdf//asdf.com"). In this case, skip the
3754 // match.
3755 if( offset > 0 && protocolRelativeMatch && this.wordCharRegExp.test( prevChar ) ) {
3756 continue;
3757 }
3758
3759 if( /\?$/.test(matchStr) ) {
3760 matchStr = matchStr.substr(0, matchStr.length-1);
3761 }
3762
3763 // Handle a closing parenthesis at the end of the match, and exclude
3764 // it if there is not a matching open parenthesis in the match
3765 // itself.
3766 if( this.matchHasUnbalancedClosingParen( matchStr ) ) {
3767 matchStr = matchStr.substr( 0, matchStr.length - 1 ); // remove the trailing ")"
3768 } else {
3769 // Handle an invalid character after the TLD
3770 var pos = this.matchHasInvalidCharAfterTld( matchStr, schemeUrlMatch );
3771 if( pos > -1 ) {
3772 matchStr = matchStr.substr( 0, pos ); // remove the trailing invalid chars
3773 }
3774 }
3775
3776 var urlMatchType = schemeUrlMatch ? 'scheme' : ( wwwUrlMatch ? 'www' : 'tld' ),
3777 protocolUrlMatch = !!schemeUrlMatch;
3778
3779 matches.push( new Autolinker.match.Url( {
3780 tagBuilder : tagBuilder,
3781 matchedText : matchStr,
3782 offset : offset,
3783 urlMatchType : urlMatchType,
3784 url : matchStr,
3785 protocolUrlMatch : protocolUrlMatch,
3786 protocolRelativeMatch : !!protocolRelativeMatch,
3787 stripPrefix : stripPrefix,
3788 stripTrailingSlash : stripTrailingSlash,
3789 decodePercentEncoding : decodePercentEncoding,
3790 } ) );
3791 }
3792
3793 return matches;
3794 },
3795
3796
3797 /**
3798 * Determines if a match found has an unmatched closing parenthesis. If so,
3799 * this parenthesis will be removed from the match itself, and appended
3800 * after the generated anchor tag.
3801 *
3802 * A match may have an extra closing parenthesis at the end of the match
3803 * because the regular expression must include parenthesis for URLs such as
3804 * "wikipedia.com/something_(disambiguation)", which should be auto-linked.
3805 *
3806 * However, an extra parenthesis *will* be included when the URL itself is
3807 * wrapped in parenthesis, such as in the case of "(wikipedia.com/something_(disambiguation))".
3808 * In this case, the last closing parenthesis should *not* be part of the
3809 * URL itself, and this method will return `true`.
3810 *
3811 * @private
3812 * @param {String} matchStr The full match string from the {@link #matcherRegex}.
3813 * @return {Boolean} `true` if there is an unbalanced closing parenthesis at
3814 * the end of the `matchStr`, `false` otherwise.
3815 */
3816 matchHasUnbalancedClosingParen : function( matchStr ) {
3817 var lastChar = matchStr.charAt( matchStr.length - 1 );
3818
3819 if( lastChar === ')' ) {
3820 var openParensMatch = matchStr.match( this.openParensRe ),
3821 closeParensMatch = matchStr.match( this.closeParensRe ),
3822 numOpenParens = ( openParensMatch && openParensMatch.length ) || 0,
3823 numCloseParens = ( closeParensMatch && closeParensMatch.length ) || 0;
3824
3825 if( numOpenParens < numCloseParens ) {
3826 return true;
3827 }
3828 }
3829
3830 return false;
3831 },
3832
3833
3834 /**
3835 * Determine if there's an invalid character after the TLD in a URL. Valid
3836 * characters after TLD are ':/?#'. Exclude scheme matched URLs from this
3837 * check.
3838 *
3839 * @private
3840 * @param {String} urlMatch The matched URL, if there was one. Will be an
3841 * empty string if the match is not a URL match.
3842 * @param {String} schemeUrlMatch The match URL string for a scheme
3843 * match. Ex: 'http://yahoo.com'. This is used to match something like
3844 * 'http://localhost', where we won't double check that the domain name
3845 * has at least one '.' in it.
3846 * @return {Number} the position where the invalid character was found. If
3847 * no such character was found, returns -1
3848 */
3849 matchHasInvalidCharAfterTld : function( urlMatch, schemeUrlMatch ) {
3850 if( !urlMatch ) {
3851 return -1;
3852 }
3853
3854 var offset = 0;
3855 if ( schemeUrlMatch ) {
3856 offset = urlMatch.indexOf(':');
3857 urlMatch = urlMatch.slice(offset);
3858 }
3859
3860 var alphaNumeric = Autolinker.RegexLib.alphaNumericCharsStr;
3861
3862 var re = new RegExp("^((.?\/\/)?[-." + alphaNumeric + "]*[-" + alphaNumeric + "]\\.[-" + alphaNumeric + "]+)");
3863 var res = re.exec( urlMatch );
3864 if ( res === null ) {
3865 return -1;
3866 }
3867
3868 offset += res[1].length;
3869 urlMatch = urlMatch.slice(res[1].length);
3870 if (/^[^-.A-Za-z0-9:\/?#]/.test(urlMatch)) {
3871 return offset;
3872 }
3873
3874 return -1;
3875 }
3876
3877 } );
3878
3879 /*global Autolinker */
3880 /*jshint scripturl:true */
3881 /**
3882 * @private
3883 * @class Autolinker.matcher.UrlMatchValidator
3884 * @singleton
3885 *
3886 * Used by Autolinker to filter out false URL positives from the
3887 * {@link Autolinker.matcher.Url UrlMatcher}.
3888 *
3889 * Due to the limitations of regular expressions (including the missing feature
3890 * of look-behinds in JS regular expressions), we cannot always determine the
3891 * validity of a given match. This class applies a bit of additional logic to
3892 * filter out any false positives that have been matched by the
3893 * {@link Autolinker.matcher.Url UrlMatcher}.
3894 */
3895 Autolinker.matcher.UrlMatchValidator = {
3896
3897 /**
3898 * Regex to test for a full protocol, with the two trailing slashes. Ex: 'http://'
3899 *
3900 * @private
3901 * @property {RegExp} hasFullProtocolRegex
3902 */
3903 hasFullProtocolRegex : /^[A-Za-z][-.+A-Za-z0-9]*:\/\//,
3904
3905 /**
3906 * Regex to find the URI scheme, such as 'mailto:'.
3907 *
3908 * This is used to filter out 'javascript:' and 'vbscript:' schemes.
3909 *
3910 * @private
3911 * @property {RegExp} uriSchemeRegex
3912 */
3913 uriSchemeRegex : /^[A-Za-z][-.+A-Za-z0-9]*:/,
3914
3915 /**
3916 * Regex to determine if at least one word char exists after the protocol (i.e. after the ':')
3917 *
3918 * @private
3919 * @property {RegExp} hasWordCharAfterProtocolRegex
3920 */
3921 hasWordCharAfterProtocolRegex : new RegExp(":[^\\s]*?[" + Autolinker.RegexLib.alphaCharsStr + "]"),
3922
3923 /**
3924 * Regex to determine if the string is a valid IP address
3925 *
3926 * @private
3927 * @property {RegExp} ipRegex
3928 */
3929 ipRegex: /[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?(:[0-9]*)?\/?$/,
3930
3931 /**
3932 * Determines if a given URL match found by the {@link Autolinker.matcher.Url UrlMatcher}
3933 * is valid. Will return `false` for:
3934 *
3935 * 1) URL matches which do not have at least have one period ('.') in the
3936 * domain name (effectively skipping over matches like "abc:def").
3937 * However, URL matches with a protocol will be allowed (ex: 'http://localhost')
3938 * 2) URL matches which do not have at least one word character in the
3939 * domain name (effectively skipping over matches like "git:1.0").
3940 * 3) A protocol-relative url match (a URL beginning with '//') whose
3941 * previous character is a word character (effectively skipping over
3942 * strings like "abc//google.com")
3943 *
3944 * Otherwise, returns `true`.
3945 *
3946 * @param {String} urlMatch The matched URL, if there was one. Will be an
3947 * empty string if the match is not a URL match.
3948 * @param {String} protocolUrlMatch The match URL string for a protocol
3949 * match. Ex: 'http://yahoo.com'. This is used to match something like
3950 * 'http://localhost', where we won't double check that the domain name
3951 * has at least one '.' in it.
3952 * @return {Boolean} `true` if the match given is valid and should be
3953 * processed, or `false` if the match is invalid and/or should just not be
3954 * processed.
3955 */
3956 isValid : function( urlMatch, protocolUrlMatch ) {
3957 if(
3958 ( protocolUrlMatch && !this.isValidUriScheme( protocolUrlMatch ) ) ||
3959 this.urlMatchDoesNotHaveProtocolOrDot( urlMatch, protocolUrlMatch ) || // At least one period ('.') must exist in the URL match for us to consider it an actual URL, *unless* it was a full protocol match (like 'http://localhost')
3960 (this.urlMatchDoesNotHaveAtLeastOneWordChar( urlMatch, protocolUrlMatch ) && // At least one letter character must exist in the domain name after a protocol match. Ex: skip over something like "git:1.0"
3961 !this.isValidIpAddress( urlMatch )) || // Except if it's an IP address
3962 this.containsMultipleDots( urlMatch )
3963 ) {
3964 return false;
3965 }
3966
3967 return true;
3968 },
3969
3970
3971 isValidIpAddress : function ( uriSchemeMatch ) {
3972 var newRegex = new RegExp(this.hasFullProtocolRegex.source + this.ipRegex.source);
3973 var uriScheme = uriSchemeMatch.match( newRegex );
3974
3975 return uriScheme !== null;
3976 },
3977
3978 containsMultipleDots : function ( urlMatch ) {
3979 var stringBeforeSlash = urlMatch;
3980 if (this.hasFullProtocolRegex.test(urlMatch)) {
3981 stringBeforeSlash = urlMatch.split('://')[1];
3982 }
3983 return stringBeforeSlash.split('/')[0].indexOf("..") > -1;
3984 },
3985
3986 /**
3987 * Determines if the URI scheme is a valid scheme to be autolinked. Returns
3988 * `false` if the scheme is 'javascript:' or 'vbscript:'
3989 *
3990 * @private
3991 * @param {String} uriSchemeMatch The match URL string for a full URI scheme
3992 * match. Ex: 'http://yahoo.com' or 'mailto:[email protected]'.
3993 * @return {Boolean} `true` if the scheme is a valid one, `false` otherwise.
3994 */
3995 isValidUriScheme : function( uriSchemeMatch ) {
3996 var uriScheme = uriSchemeMatch.match( this.uriSchemeRegex )[ 0 ].toLowerCase();
3997
3998 return ( uriScheme !== 'javascript:' && uriScheme !== 'vbscript:' );
3999 },
4000
4001
4002 /**
4003 * Determines if a URL match does not have either:
4004 *
4005 * a) a full protocol (i.e. 'http://'), or
4006 * b) at least one dot ('.') in the domain name (for a non-full-protocol
4007 * match).
4008 *
4009 * Either situation is considered an invalid URL (ex: 'git:d' does not have
4010 * either the '://' part, or at least one dot in the domain name. If the
4011 * match was 'git:abc.com', we would consider this valid.)
4012 *
4013 * @private
4014 * @param {String} urlMatch The matched URL, if there was one. Will be an
4015 * empty string if the match is not a URL match.
4016 * @param {String} protocolUrlMatch The match URL string for a protocol
4017 * match. Ex: 'http://yahoo.com'. This is used to match something like
4018 * 'http://localhost', where we won't double check that the domain name
4019 * has at least one '.' in it.
4020 * @return {Boolean} `true` if the URL match does not have a full protocol,
4021 * or at least one dot ('.') in a non-full-protocol match.
4022 */
4023 urlMatchDoesNotHaveProtocolOrDot : function( urlMatch, protocolUrlMatch ) {
4024 return ( !!urlMatch && ( !protocolUrlMatch || !this.hasFullProtocolRegex.test( protocolUrlMatch ) ) && urlMatch.indexOf( '.' ) === -1 );
4025 },
4026
4027
4028 /**
4029 * Determines if a URL match does not have at least one word character after
4030 * the protocol (i.e. in the domain name).
4031 *
4032 * At least one letter character must exist in the domain name after a
4033 * protocol match. Ex: skip over something like "git:1.0"
4034 *
4035 * @private
4036 * @param {String} urlMatch The matched URL, if there was one. Will be an
4037 * empty string if the match is not a URL match.
4038 * @param {String} protocolUrlMatch The match URL string for a protocol
4039 * match. Ex: 'http://yahoo.com'. This is used to know whether or not we
4040 * have a protocol in the URL string, in order to check for a word
4041 * character after the protocol separator (':').
4042 * @return {Boolean} `true` if the URL match does not have at least one word
4043 * character in it after the protocol, `false` otherwise.
4044 */
4045 urlMatchDoesNotHaveAtLeastOneWordChar : function( urlMatch, protocolUrlMatch ) {
4046 if( urlMatch && protocolUrlMatch ) {
4047 return !this.hasWordCharAfterProtocolRegex.test( urlMatch );
4048 } else {
4049 return false;
4050 }
4051 }
4052
4053 };
4054
4055 /*global Autolinker */
4056 /**
4057 * A truncation feature where the ellipsis will be placed at the end of the URL.
4058 *
4059 * @param {String} anchorText
4060 * @param {Number} truncateLen The maximum length of the truncated output URL string.
4061 * @param {String} ellipsisChars The characters to place within the url, e.g. "..".
4062 * @return {String} The truncated URL.
4063 */
4064 Autolinker.truncate.TruncateEnd = function(anchorText, truncateLen, ellipsisChars){
4065 return Autolinker.Util.ellipsis( anchorText, truncateLen, ellipsisChars );
4066 };
4067
4068 /*global Autolinker */
4069 /**
4070 * Date: 2015-10-05
4071 * Author: Kasper Søfren <[email protected]> (https://github.com/kafoso)
4072 *
4073 * A truncation feature, where the ellipsis will be placed in the dead-center of the URL.
4074 *
4075 * @param {String} url A URL.
4076 * @param {Number} truncateLen The maximum length of the truncated output URL string.
4077 * @param {String} ellipsisChars The characters to place within the url, e.g. "..".
4078 * @return {String} The truncated URL.
4079 */
4080 Autolinker.truncate.TruncateMiddle = function(url, truncateLen, ellipsisChars){
4081 if (url.length <= truncateLen) {
4082 return url;
4083 }
4084
4085 var ellipsisLengthBeforeParsing;
4086 var ellipsisLength;
4087
4088 if(ellipsisChars == null) {
4089 ellipsisChars = '&hellip;';
4090 ellipsisLengthBeforeParsing = 8;
4091 ellipsisLength = 3;
4092 } else {
4093 ellipsisLengthBeforeParsing = ellipsisChars.length;
4094 ellipsisLength = ellipsisChars.length;
4095 }
4096
4097 var availableLength = truncateLen - ellipsisLength;
4098 var end = "";
4099 if (availableLength > 0) {
4100 end = url.substr((-1)*Math.floor(availableLength/2));
4101 }
4102 return (url.substr(0, Math.ceil(availableLength/2)) + ellipsisChars + end).substr(0, availableLength + ellipsisLengthBeforeParsing);
4103 };
4104
4105 /*global Autolinker */
4106 /**
4107 * Date: 2015-10-05
4108 * Author: Kasper Søfren <[email protected]> (https://github.com/kafoso)
4109 *
4110 * A truncation feature, where the ellipsis will be placed at a section within
4111 * the URL making it still somewhat human readable.
4112 *
4113 * @param {String} url A URL.
4114 * @param {Number} truncateLen The maximum length of the truncated output URL string.
4115 * @param {String} ellipsisChars The characters to place within the url, e.g. "...".
4116 * @return {String} The truncated URL.
4117 */
4118 Autolinker.truncate.TruncateSmart = function(url, truncateLen, ellipsisChars){
4119
4120 var ellipsisLengthBeforeParsing;
4121 var ellipsisLength;
4122
4123 if(ellipsisChars == null) {
4124 ellipsisChars = '&hellip;';
4125 ellipsisLength = 3;
4126 ellipsisLengthBeforeParsing = 8;
4127 } else {
4128 ellipsisLength = ellipsisChars.length;
4129 ellipsisLengthBeforeParsing = ellipsisChars.length;
4130 }
4131
4132 var parse_url = function(url){ // Functionality inspired by PHP function of same name
4133 var urlObj = {};
4134 var urlSub = url;
4135 var match = urlSub.match(/^([a-z]+):\/\//i);
4136 if (match) {
4137 urlObj.scheme = match[1];
4138 urlSub = urlSub.substr(match[0].length);
4139 }
4140 match = urlSub.match(/^(.*?)(?=(\?|#|\/|$))/i);
4141 if (match) {
4142 urlObj.host = match[1];
4143 urlSub = urlSub.substr(match[0].length);
4144 }
4145 match = urlSub.match(/^\/(.*?)(?=(\?|#|$))/i);
4146 if (match) {
4147 urlObj.path = match[1];
4148 urlSub = urlSub.substr(match[0].length);
4149 }
4150 match = urlSub.match(/^\?(.*?)(?=(#|$))/i);
4151 if (match) {
4152 urlObj.query = match[1];
4153 urlSub = urlSub.substr(match[0].length);
4154 }
4155 match = urlSub.match(/^#(.*?)$/i);
4156 if (match) {
4157 urlObj.fragment = match[1];
4158 //urlSub = urlSub.substr(match[0].length); -- not used. Uncomment if adding another block.
4159 }
4160 return urlObj;
4161 };
4162
4163 var buildUrl = function(urlObj){
4164 var url = "";
4165 if (urlObj.scheme && urlObj.host) {
4166 url += urlObj.scheme + "://";
4167 }
4168 if (urlObj.host) {
4169 url += urlObj.host;
4170 }
4171 if (urlObj.path) {
4172 url += "/" + urlObj.path;
4173 }
4174 if (urlObj.query) {
4175 url += "?" + urlObj.query;
4176 }
4177 if (urlObj.fragment) {
4178 url += "#" + urlObj.fragment;
4179 }
4180 return url;
4181 };
4182
4183 var buildSegment = function(segment, remainingAvailableLength){
4184 var remainingAvailableLengthHalf = remainingAvailableLength/ 2,
4185 startOffset = Math.ceil(remainingAvailableLengthHalf),
4186 endOffset = (-1)*Math.floor(remainingAvailableLengthHalf),
4187 end = "";
4188 if (endOffset < 0) {
4189 end = segment.substr(endOffset);
4190 }
4191 return segment.substr(0, startOffset) + ellipsisChars + end;
4192 };
4193 if (url.length <= truncateLen) {
4194 return url;
4195 }
4196 var availableLength = truncateLen - ellipsisLength;
4197 var urlObj = parse_url(url);
4198 // Clean up the URL
4199 if (urlObj.query) {
4200 var matchQuery = urlObj.query.match(/^(.*?)(?=(\?|\#))(.*?)$/i);
4201 if (matchQuery) {
4202 // Malformed URL; two or more "?". Removed any content behind the 2nd.
4203 urlObj.query = urlObj.query.substr(0, matchQuery[1].length);
4204 url = buildUrl(urlObj);
4205 }
4206 }
4207 if (url.length <= truncateLen) {
4208 return url;
4209 }
4210 if (urlObj.host) {
4211 urlObj.host = urlObj.host.replace(/^www\./, "");
4212 url = buildUrl(urlObj);
4213 }
4214 if (url.length <= truncateLen) {
4215 return url;
4216 }
4217 // Process and build the URL
4218 var str = "";
4219 if (urlObj.host) {
4220 str += urlObj.host;
4221 }
4222 if (str.length >= availableLength) {
4223 if (urlObj.host.length == truncateLen) {
4224 return (urlObj.host.substr(0, (truncateLen - ellipsisLength)) + ellipsisChars).substr(0, availableLength + ellipsisLengthBeforeParsing);
4225 }
4226 return buildSegment(str, availableLength).substr(0, availableLength + ellipsisLengthBeforeParsing);
4227 }
4228 var pathAndQuery = "";
4229 if (urlObj.path) {
4230 pathAndQuery += "/" + urlObj.path;
4231 }
4232 if (urlObj.query) {
4233 pathAndQuery += "?" + urlObj.query;
4234 }
4235 if (pathAndQuery) {
4236 if ((str+pathAndQuery).length >= availableLength) {
4237 if ((str+pathAndQuery).length == truncateLen) {
4238 return (str + pathAndQuery).substr(0, truncateLen);
4239 }
4240 var remainingAvailableLength = availableLength - str.length;
4241 return (str + buildSegment(pathAndQuery, remainingAvailableLength)).substr(0, availableLength + ellipsisLengthBeforeParsing);
4242 } else {
4243 str += pathAndQuery;
4244 }
4245 }
4246 if (urlObj.fragment) {
4247 var fragment = "#"+urlObj.fragment;
4248 if ((str+fragment).length >= availableLength) {
4249 if ((str+fragment).length == truncateLen) {
4250 return (str + fragment).substr(0, truncateLen);
4251 }
4252 var remainingAvailableLength2 = availableLength - str.length;
4253 return (str + buildSegment(fragment, remainingAvailableLength2)).substr(0, availableLength + ellipsisLengthBeforeParsing);
4254 } else {
4255 str += fragment;
4256 }
4257 }
4258 if (urlObj.scheme && urlObj.host) {
4259 var scheme = urlObj.scheme + "://";
4260 if ((str+scheme).length < availableLength) {
4261 return (scheme + str).substr(0, truncateLen);
4262 }
4263 }
4264 if (str.length <= truncateLen) {
4265 return str;
4266 }
4267 var end = "";
4268 if (availableLength > 0) {
4269 end = str.substr((-1)*Math.floor(availableLength/2));
4270 }
4271 return (str.substr(0, Math.ceil(availableLength/2)) + ellipsisChars + end).substr(0, availableLength + ellipsisLengthBeforeParsing);
4272 };
4273
4274 return Autolinker;
4275 }));