| 1 | /** |
| 2 | * @class Autolinker |
| 3 | * @extends Object |
| 4 | * |
| 5 | * Utility class used to process a given string of text, and wrap the matches in |
| 6 | * the appropriate anchor (<a>) tags to turn them into links. |
| 7 | * |
| 8 | * Any of the configuration options may be provided in an Object (map) provided |
| 9 | * to the Autolinker constructor, which will configure how the {@link #link link()} |
| 10 | * method will process the links. |
| 11 | * |
| 12 | * For example: |
| 13 | * |
| 14 | * var autolinker = new Autolinker( { |
| 15 | * newWindow : false, |
| 16 | * truncate : 30 |
| 17 | * } ); |
| 18 | * |
| 19 | * var html = autolinker.link( "Joe went to www.yahoo.com" ); |
| 20 | * // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>' |
| 21 | * |
| 22 | * |
| 23 | * The {@link #static-link static link()} method may also be used to inline |
| 24 | * options into a single call, which may be more convenient for one-off uses. |
| 25 | * For example: |
| 26 | * |
| 27 | * var html = Autolinker.link( "Joe went to www.yahoo.com", { |
| 28 | * newWindow : false, |
| 29 | * truncate : 30 |
| 30 | * } ); |
| 31 | * // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>' |
| 32 | * |
| 33 | * |
| 34 | * ## Custom Replacements of Links |
| 35 | * |
| 36 | * If the configuration options do not provide enough flexibility, a {@link #replaceFn} |
| 37 | * may be provided to fully customize the output of Autolinker. This function is |
| 38 | * called once for each URL/Email/Phone#/Hashtag/Mention (Twitter, Instagram, Soundcloud) |
| 39 | * match that is encountered. |
| 40 | * |
| 41 | * For example: |
| 42 | * |
| 43 | * var input = "..."; // string with URLs, Email Addresses, Phone #s, Hashtags, and Mentions (Twitter, Instagram, Soundcloud) |
| 44 | * |
| 45 | * var linkedText = Autolinker.link( input, { |
| 46 | * replaceFn : function( match ) { |
| 47 | * console.log( "href = ", match.getAnchorHref() ); |
| 48 | * console.log( "text = ", match.getAnchorText() ); |
| 49 | * |
| 50 | * switch( match.getType() ) { |
| 51 | * case 'url' : |
| 52 | * console.log( "url: ", match.getUrl() ); |
| 53 | * |
| 54 | * if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) { |
| 55 | * var tag = match.buildTag(); // returns an `Autolinker.HtmlTag` instance, which provides mutator methods for easy changes |
| 56 | * tag.setAttr( 'rel', 'nofollow' ); |
| 57 | * tag.addClass( 'external-link' ); |
| 58 | * |
| 59 | * return tag; |
| 60 | * |
| 61 | * } else { |
| 62 | * return true; // let Autolinker perform its normal anchor tag replacement |
| 63 | * } |
| 64 | * |
| 65 | * case 'email' : |
| 66 | * var email = match.getEmail(); |
| 67 | * console.log( "email: ", email ); |
| 68 | * |
| 69 | * if( email === "[email protected]" ) { |
| 70 | * return false; // don't auto-link this particular email address; leave as-is |
| 71 | * } else { |
| 72 | * return; // no return value will have Autolinker perform its normal anchor tag replacement (same as returning `true`) |
| 73 | * } |
| 74 | * |
| 75 | * case 'phone' : |
| 76 | * var phoneNumber = match.getPhoneNumber(); |
| 77 | * console.log( phoneNumber ); |
| 78 | * |
| 79 | * return '<a href="http://newplace.to.link.phone.numbers.to/">' + phoneNumber + '</a>'; |
| 80 | * |
| 81 | * case 'hashtag' : |
| 82 | * var hashtag = match.getHashtag(); |
| 83 | * console.log( hashtag ); |
| 84 | * |
| 85 | * return '<a href="http://newplace.to.link.hashtag.handles.to/">' + hashtag + '</a>'; |
| 86 | * |
| 87 | * case 'mention' : |
| 88 | * var mention = match.getMention(); |
| 89 | * console.log( mention ); |
| 90 | * |
| 91 | * return '<a href="http://newplace.to.link.mention.to/">' + mention + '</a>'; |
| 92 | * } |
| 93 | * } |
| 94 | * } ); |
| 95 | * |
| 96 | * |
| 97 | * The function may return the following values: |
| 98 | * |
| 99 | * - `true` (Boolean): Allow Autolinker to replace the match as it normally |
| 100 | * would. |
| 101 | * - `false` (Boolean): Do not replace the current match at all - leave as-is. |
| 102 | * - Any String: If a string is returned from the function, the string will be |
| 103 | * used directly as the replacement HTML for the match. |
| 104 | * - An {@link Autolinker.HtmlTag} instance, which can be used to build/modify |
| 105 | * an HTML tag before writing out its HTML text. |
| 106 | * |
| 107 | * @constructor |
| 108 | * @param {Object} [cfg] The configuration options for the Autolinker instance, |
| 109 | * specified in an Object (map). |
| 110 | */ |
| 111 | var Autolinker = function( cfg ) { |
| 112 | cfg = cfg || {}; |
| 113 | |
| 114 | this.version = Autolinker.version; |
| 115 | |
| 116 | this.urls = this.normalizeUrlsCfg( cfg.urls ); |
| 117 | this.email = typeof cfg.email === 'boolean' ? cfg.email : true; |
| 118 | this.phone = typeof cfg.phone === 'boolean' ? cfg.phone : true; |
| 119 | this.hashtag = cfg.hashtag || false; |
| 120 | this.mention = cfg.mention || false; |
| 121 | this.newWindow = typeof cfg.newWindow === 'boolean' ? cfg.newWindow : true; |
| 122 | this.stripPrefix = this.normalizeStripPrefixCfg( cfg.stripPrefix ); |
| 123 | this.stripTrailingSlash = typeof cfg.stripTrailingSlash === 'boolean' ? cfg.stripTrailingSlash : true; |
| 124 | this.decodePercentEncoding = typeof cfg.decodePercentEncoding === 'boolean' ? cfg.decodePercentEncoding : true; |
| 125 | |
| 126 | // Validate the value of the `mention` cfg |
| 127 | var mention = this.mention; |
| 128 | if( mention !== false && mention !== 'twitter' && mention !== 'instagram' && mention !== 'soundcloud' ) { |
| 129 | throw new Error( "invalid `mention` cfg - see docs" ); |
| 130 | } |
| 131 | |
| 132 | // Validate the value of the `hashtag` cfg |
| 133 | var hashtag = this.hashtag; |
| 134 | if( hashtag !== false && hashtag !== 'twitter' && hashtag !== 'facebook' && hashtag !== 'instagram' ) { |
| 135 | throw new Error( "invalid `hashtag` cfg - see docs" ); |
| 136 | } |
| 137 | |
| 138 | this.truncate = this.normalizeTruncateCfg( cfg.truncate ); |
| 139 | this.className = cfg.className || ''; |
| 140 | this.replaceFn = cfg.replaceFn || null; |
| 141 | this.context = cfg.context || this; |
| 142 | |
| 143 | this.htmlParser = null; |
| 144 | this.matchers = null; |
| 145 | this.tagBuilder = null; |
| 146 | }; |
| 147 | |
| 148 | |
| 149 | |
| 150 | /** |
| 151 | * Automatically links URLs, Email addresses, Phone Numbers, Twitter handles, |
| 152 | * Hashtags, and Mentions found in the given chunk of HTML. Does not link URLs |
| 153 | * found within HTML tags. |
| 154 | * |
| 155 | * For instance, if given the text: `You should go to http://www.yahoo.com`, |
| 156 | * then the result will be `You should go to <a href="http://www.yahoo.com">http://www.yahoo.com</a>` |
| 157 | * |
| 158 | * Example: |
| 159 | * |
| 160 | * var linkedText = Autolinker.link( "Go to google.com", { newWindow: false } ); |
| 161 | * // Produces: "Go to <a href="http://google.com">google.com</a>" |
| 162 | * |
| 163 | * @static |
| 164 | * @param {String} textOrHtml The HTML or text to find matches within (depending |
| 165 | * on if the {@link #urls}, {@link #email}, {@link #phone}, {@link #mention}, |
| 166 | * {@link #hashtag}, and {@link #mention} options are enabled). |
| 167 | * @param {Object} [options] Any of the configuration options for the Autolinker |
| 168 | * class, specified in an Object (map). See the class description for an |
| 169 | * example call. |
| 170 | * @return {String} The HTML text, with matches automatically linked. |
| 171 | */ |
| 172 | Autolinker.link = function( textOrHtml, options ) { |
| 173 | var autolinker = new Autolinker( options ); |
| 174 | return autolinker.link( textOrHtml ); |
| 175 | }; |
| 176 | |
| 177 | |
| 178 | |
| 179 | /** |
| 180 | * Parses the input `textOrHtml` looking for URLs, email addresses, phone |
| 181 | * numbers, username handles, and hashtags (depending on the configuration |
| 182 | * of the Autolinker instance), and returns an array of {@link Autolinker.match.Match} |
| 183 | * objects describing those matches (without making any replacements). |
| 184 | * |
| 185 | * Note that if parsing multiple pieces of text, it is slightly more efficient |
| 186 | * to create an Autolinker instance, and use the instance-level {@link #parse} |
| 187 | * method. |
| 188 | * |
| 189 | * Example: |
| 190 | * |
| 191 | * var matches = Autolinker.parse( "Hello google.com, I am [email protected]", { |
| 192 | * urls: true, |
| 193 | * email: true |
| 194 | * } ); |
| 195 | * |
| 196 | * console.log( matches.length ); // 2 |
| 197 | * console.log( matches[ 0 ].getType() ); // 'url' |
| 198 | * console.log( matches[ 0 ].getUrl() ); // 'google.com' |
| 199 | * console.log( matches[ 1 ].getType() ); // 'email' |
| 200 | * console.log( matches[ 1 ].getEmail() ); // '[email protected]' |
| 201 | * |
| 202 | * @static |
| 203 | * @param {String} textOrHtml The HTML or text to find matches within |
| 204 | * (depending on if the {@link #urls}, {@link #email}, {@link #phone}, |
| 205 | * {@link #hashtag}, and {@link #mention} options are enabled). |
| 206 | * @param {Object} [options] Any of the configuration options for the Autolinker |
| 207 | * class, specified in an Object (map). See the class description for an |
| 208 | * example call. |
| 209 | * @return {Autolinker.match.Match[]} The array of Matches found in the |
| 210 | * given input `textOrHtml`. |
| 211 | */ |
| 212 | Autolinker.parse = function( textOrHtml, options ) { |
| 213 | var autolinker = new Autolinker( options ); |
| 214 | return autolinker.parse( textOrHtml ); |
| 215 | }; |
| 216 | |
| 217 | |
| 218 | /** |
| 219 | * @static |
| 220 | * @property {String} version (readonly) |
| 221 | * |
| 222 | * The Autolinker version number in the form major.minor.patch |
| 223 | * |
| 224 | * Ex: 0.25.1 |
| 225 | */ |
| 226 | Autolinker.version = '/* @echo VERSION */'; |
| 227 | |
| 228 | |
| 229 | Autolinker.prototype = { |
| 230 | constructor : Autolinker, // fix constructor property |
| 231 | |
| 232 | /** |
| 233 | * @cfg {Boolean/Object} [urls] |
| 234 | * |
| 235 | * `true` if URLs should be automatically linked, `false` if they should not |
| 236 | * be. Defaults to `true`. |
| 237 | * |
| 238 | * Examples: |
| 239 | * |
| 240 | * urls: true |
| 241 | * |
| 242 | * // or |
| 243 | * |
| 244 | * urls: { |
| 245 | * schemeMatches : true, |
| 246 | * wwwMatches : true, |
| 247 | * tldMatches : true |
| 248 | * } |
| 249 | * |
| 250 | * As shown above, this option also accepts an Object form with 3 properties |
| 251 | * to allow for more customization of what exactly gets linked. All default |
| 252 | * to `true`: |
| 253 | * |
| 254 | * @cfg {Boolean} [urls.schemeMatches] `true` to match URLs found prefixed |
| 255 | * with a scheme, i.e. `http://google.com`, or `other+scheme://google.com`, |
| 256 | * `false` to prevent these types of matches. |
| 257 | * @cfg {Boolean} [urls.wwwMatches] `true` to match urls found prefixed with |
| 258 | * `'www.'`, i.e. `www.google.com`. `false` to prevent these types of |
| 259 | * matches. Note that if the URL had a prefixed scheme, and |
| 260 | * `schemeMatches` is true, it will still be linked. |
| 261 | * @cfg {Boolean} [urls.tldMatches] `true` to match URLs with known top |
| 262 | * level domains (.com, .net, etc.) that are not prefixed with a scheme or |
| 263 | * `'www.'`. This option attempts to match anything that looks like a URL |
| 264 | * in the given text. Ex: `google.com`, `asdf.org/?page=1`, etc. `false` |
| 265 | * to prevent these types of matches. |
| 266 | */ |
| 267 | |
| 268 | /** |
| 269 | * @cfg {Boolean} [email=true] |
| 270 | * |
| 271 | * `true` if email addresses should be automatically linked, `false` if they |
| 272 | * should not be. |
| 273 | */ |
| 274 | |
| 275 | /** |
| 276 | * @cfg {Boolean} [phone=true] |
| 277 | * |
| 278 | * `true` if Phone numbers ("(555)555-5555") should be automatically linked, |
| 279 | * `false` if they should not be. |
| 280 | */ |
| 281 | |
| 282 | /** |
| 283 | * @cfg {Boolean/String} [hashtag=false] |
| 284 | * |
| 285 | * A string for the service name to have hashtags (ex: "#myHashtag") |
| 286 | * auto-linked to. The currently-supported values are: |
| 287 | * |
| 288 | * - 'twitter' |
| 289 | * - 'facebook' |
| 290 | * - 'instagram' |
| 291 | * |
| 292 | * Pass `false` to skip auto-linking of hashtags. |
| 293 | */ |
| 294 | |
| 295 | /** |
| 296 | * @cfg {String/Boolean} [mention=false] |
| 297 | * |
| 298 | * A string for the service name to have mentions (ex: "@myuser") |
| 299 | * auto-linked to. The currently supported values are: |
| 300 | * |
| 301 | * - 'twitter' |
| 302 | * - 'instagram' |
| 303 | * - 'soundcloud' |
| 304 | * |
| 305 | * Defaults to `false` to skip auto-linking of mentions. |
| 306 | */ |
| 307 | |
| 308 | /** |
| 309 | * @cfg {Boolean} [newWindow=true] |
| 310 | * |
| 311 | * `true` if the links should open in a new window, `false` otherwise. |
| 312 | */ |
| 313 | |
| 314 | /** |
| 315 | * @cfg {Boolean/Object} [stripPrefix] |
| 316 | * |
| 317 | * `true` if 'http://' (or 'https://') and/or the 'www.' should be stripped |
| 318 | * from the beginning of URL links' text, `false` otherwise. Defaults to |
| 319 | * `true`. |
| 320 | * |
| 321 | * Examples: |
| 322 | * |
| 323 | * stripPrefix: true |
| 324 | * |
| 325 | * // or |
| 326 | * |
| 327 | * stripPrefix: { |
| 328 | * scheme : true, |
| 329 | * www : true |
| 330 | * } |
| 331 | * |
| 332 | * As shown above, this option also accepts an Object form with 2 properties |
| 333 | * to allow for more customization of what exactly is prevented from being |
| 334 | * displayed. Both default to `true`: |
| 335 | * |
| 336 | * @cfg {Boolean} [stripPrefix.scheme] `true` to prevent the scheme part of |
| 337 | * a URL match from being displayed to the user. Example: |
| 338 | * `'http://google.com'` will be displayed as `'google.com'`. `false` to |
| 339 | * not strip the scheme. NOTE: Only an `'http://'` or `'https://'` scheme |
| 340 | * will be removed, so as not to remove a potentially dangerous scheme |
| 341 | * (such as `'file://'` or `'javascript:'`) |
| 342 | * @cfg {Boolean} [stripPrefix.www] www (Boolean): `true` to prevent the |
| 343 | * `'www.'` part of a URL match from being displayed to the user. Ex: |
| 344 | * `'www.google.com'` will be displayed as `'google.com'`. `false` to not |
| 345 | * strip the `'www'`. |
| 346 | */ |
| 347 | |
| 348 | /** |
| 349 | * @cfg {Boolean} [stripTrailingSlash=true] |
| 350 | * |
| 351 | * `true` to remove the trailing slash from URL matches, `false` to keep |
| 352 | * the trailing slash. |
| 353 | * |
| 354 | * Example when `true`: `http://google.com/` will be displayed as |
| 355 | * `http://google.com`. |
| 356 | */ |
| 357 | |
| 358 | /** |
| 359 | * @cfg {Boolean} [decodePercentEncoding=true] |
| 360 | * |
| 361 | * `true` to decode percent-encoded characters in URL matches, `false` to keep |
| 362 | * the percent-encoded characters. |
| 363 | * |
| 364 | * Example when `true`: `https://en.wikipedia.org/wiki/San_Jos%C3%A9` will |
| 365 | * be displayed as `https://en.wikipedia.org/wiki/San_José`. |
| 366 | */ |
| 367 | |
| 368 | /** |
| 369 | * @cfg {Number/Object} [truncate=0] |
| 370 | * |
| 371 | * ## Number Form |
| 372 | * |
| 373 | * A number for how many characters matched text should be truncated to |
| 374 | * inside the text of a link. If the matched text is over this number of |
| 375 | * characters, it will be truncated to this length by adding a two period |
| 376 | * ellipsis ('..') to the end of the string. |
| 377 | * |
| 378 | * For example: A url like 'http://www.yahoo.com/some/long/path/to/a/file' |
| 379 | * truncated to 25 characters might look something like this: |
| 380 | * 'yahoo.com/some/long/pat..' |
| 381 | * |
| 382 | * Example Usage: |
| 383 | * |
| 384 | * truncate: 25 |
| 385 | * |
| 386 | * |
| 387 | * Defaults to `0` for "no truncation." |
| 388 | * |
| 389 | * |
| 390 | * ## Object Form |
| 391 | * |
| 392 | * An Object may also be provided with two properties: `length` (Number) and |
| 393 | * `location` (String). `location` may be one of the following: 'end' |
| 394 | * (default), 'middle', or 'smart'. |
| 395 | * |
| 396 | * Example Usage: |
| 397 | * |
| 398 | * truncate: { length: 25, location: 'middle' } |
| 399 | * |
| 400 | * @cfg {Number} [truncate.length=0] How many characters to allow before |
| 401 | * truncation will occur. Defaults to `0` for "no truncation." |
| 402 | * @cfg {"end"/"middle"/"smart"} [truncate.location="end"] |
| 403 | * |
| 404 | * - 'end' (default): will truncate up to the number of characters, and then |
| 405 | * add an ellipsis at the end. Ex: 'yahoo.com/some/long/pat..' |
| 406 | * - 'middle': will truncate and add the ellipsis in the middle. Ex: |
| 407 | * 'yahoo.com/s..th/to/a/file' |
| 408 | * - 'smart': for URLs where the algorithm attempts to strip out unnecessary |
| 409 | * parts first (such as the 'www.', then URL scheme, hash, etc.), |
| 410 | * attempting to make the URL human-readable before looking for a good |
| 411 | * point to insert the ellipsis if it is still too long. Ex: |
| 412 | * 'yahoo.com/some..to/a/file'. For more details, see |
| 413 | * {@link Autolinker.truncate.TruncateSmart}. |
| 414 | */ |
| 415 | |
| 416 | /** |
| 417 | * @cfg {String} className |
| 418 | * |
| 419 | * A CSS class name to add to the generated links. This class will be added |
| 420 | * to all links, as well as this class plus match suffixes for styling |
| 421 | * url/email/phone/hashtag/mention links differently. |
| 422 | * |
| 423 | * For example, if this config is provided as "myLink", then: |
| 424 | * |
| 425 | * - URL links will have the CSS classes: "myLink myLink-url" |
| 426 | * - Email links will have the CSS classes: "myLink myLink-email", and |
| 427 | * - Phone links will have the CSS classes: "myLink myLink-phone" |
| 428 | * - Hashtag links will have the CSS classes: "myLink myLink-hashtag" |
| 429 | * - Mention links will have the CSS classes: "myLink myLink-mention myLink-[type]" |
| 430 | * where [type] is either "instagram", "twitter" or "soundcloud" |
| 431 | */ |
| 432 | |
| 433 | /** |
| 434 | * @cfg {Function} replaceFn |
| 435 | * |
| 436 | * A function to individually process each match found in the input string. |
| 437 | * |
| 438 | * See the class's description for usage. |
| 439 | * |
| 440 | * The `replaceFn` can be called with a different context object (`this` |
| 441 | * reference) using the {@link #context} cfg. |
| 442 | * |
| 443 | * This function is called with the following parameter: |
| 444 | * |
| 445 | * @cfg {Autolinker.match.Match} replaceFn.match The Match instance which |
| 446 | * can be used to retrieve information about the match that the `replaceFn` |
| 447 | * is currently processing. See {@link Autolinker.match.Match} subclasses |
| 448 | * for details. |
| 449 | */ |
| 450 | |
| 451 | /** |
| 452 | * @cfg {Object} context |
| 453 | * |
| 454 | * The context object (`this` reference) to call the `replaceFn` with. |
| 455 | * |
| 456 | * Defaults to this Autolinker instance. |
| 457 | */ |
| 458 | |
| 459 | |
| 460 | /** |
| 461 | * @property {String} version (readonly) |
| 462 | * |
| 463 | * The Autolinker version number in the form major.minor.patch |
| 464 | * |
| 465 | * Ex: 0.25.1 |
| 466 | */ |
| 467 | |
| 468 | /** |
| 469 | * @private |
| 470 | * @property {Autolinker.htmlParser.HtmlParser} htmlParser |
| 471 | * |
| 472 | * The HtmlParser instance used to skip over HTML tags, while finding text |
| 473 | * nodes to process. This is lazily instantiated in the {@link #getHtmlParser} |
| 474 | * method. |
| 475 | */ |
| 476 | |
| 477 | /** |
| 478 | * @private |
| 479 | * @property {Autolinker.matcher.Matcher[]} matchers |
| 480 | * |
| 481 | * The {@link Autolinker.matcher.Matcher} instances for this Autolinker |
| 482 | * instance. |
| 483 | * |
| 484 | * This is lazily created in {@link #getMatchers}. |
| 485 | */ |
| 486 | |
| 487 | /** |
| 488 | * @private |
| 489 | * @property {Autolinker.AnchorTagBuilder} tagBuilder |
| 490 | * |
| 491 | * The AnchorTagBuilder instance used to build match replacement anchor tags. |
| 492 | * Note: this is lazily instantiated in the {@link #getTagBuilder} method. |
| 493 | */ |
| 494 | |
| 495 | |
| 496 | /** |
| 497 | * Normalizes the {@link #urls} config into an Object with 3 properties: |
| 498 | * `schemeMatches`, `wwwMatches`, and `tldMatches`, all Booleans. |
| 499 | * |
| 500 | * See {@link #urls} config for details. |
| 501 | * |
| 502 | * @private |
| 503 | * @param {Boolean/Object} urls |
| 504 | * @return {Object} |
| 505 | */ |
| 506 | normalizeUrlsCfg : function( urls ) { |
| 507 | if( urls == null ) urls = true; // default to `true` |
| 508 | |
| 509 | if( typeof urls === 'boolean' ) { |
| 510 | return { schemeMatches: urls, wwwMatches: urls, tldMatches: urls }; |
| 511 | |
| 512 | } else { // object form |
| 513 | return { |
| 514 | schemeMatches : typeof urls.schemeMatches === 'boolean' ? urls.schemeMatches : true, |
| 515 | wwwMatches : typeof urls.wwwMatches === 'boolean' ? urls.wwwMatches : true, |
| 516 | tldMatches : typeof urls.tldMatches === 'boolean' ? urls.tldMatches : true |
| 517 | }; |
| 518 | } |
| 519 | }, |
| 520 | |
| 521 | |
| 522 | /** |
| 523 | * Normalizes the {@link #stripPrefix} config into an Object with 2 |
| 524 | * properties: `scheme`, and `www` - both Booleans. |
| 525 | * |
| 526 | * See {@link #stripPrefix} config for details. |
| 527 | * |
| 528 | * @private |
| 529 | * @param {Boolean/Object} stripPrefix |
| 530 | * @return {Object} |
| 531 | */ |
| 532 | normalizeStripPrefixCfg : function( stripPrefix ) { |
| 533 | if( stripPrefix == null ) stripPrefix = true; // default to `true` |
| 534 | |
| 535 | if( typeof stripPrefix === 'boolean' ) { |
| 536 | return { scheme: stripPrefix, www: stripPrefix }; |
| 537 | |
| 538 | } else { // object form |
| 539 | return { |
| 540 | scheme : typeof stripPrefix.scheme === 'boolean' ? stripPrefix.scheme : true, |
| 541 | www : typeof stripPrefix.www === 'boolean' ? stripPrefix.www : true |
| 542 | }; |
| 543 | } |
| 544 | }, |
| 545 | |
| 546 | |
| 547 | /** |
| 548 | * Normalizes the {@link #truncate} config into an Object with 2 properties: |
| 549 | * `length` (Number), and `location` (String). |
| 550 | * |
| 551 | * See {@link #truncate} config for details. |
| 552 | * |
| 553 | * @private |
| 554 | * @param {Number/Object} truncate |
| 555 | * @return {Object} |
| 556 | */ |
| 557 | normalizeTruncateCfg : function( truncate ) { |
| 558 | if( typeof truncate === 'number' ) { |
| 559 | return { length: truncate, location: 'end' }; |
| 560 | |
| 561 | } else { // object, or undefined/null |
| 562 | return Autolinker.Util.defaults( truncate || {}, { |
| 563 | length : Number.POSITIVE_INFINITY, |
| 564 | location : 'end' |
| 565 | } ); |
| 566 | } |
| 567 | }, |
| 568 | |
| 569 | |
| 570 | /** |
| 571 | * Parses the input `textOrHtml` looking for URLs, email addresses, phone |
| 572 | * numbers, username handles, and hashtags (depending on the configuration |
| 573 | * of the Autolinker instance), and returns an array of {@link Autolinker.match.Match} |
| 574 | * objects describing those matches (without making any replacements). |
| 575 | * |
| 576 | * This method is used by the {@link #link} method, but can also be used to |
| 577 | * simply do parsing of the input in order to discover what kinds of links |
| 578 | * there are and how many. |
| 579 | * |
| 580 | * Example usage: |
| 581 | * |
| 582 | * var autolinker = new Autolinker( { |
| 583 | * urls: true, |
| 584 | * email: true |
| 585 | * } ); |
| 586 | * |
| 587 | * var matches = autolinker.parse( "Hello google.com, I am [email protected]" ); |
| 588 | * |
| 589 | * console.log( matches.length ); // 2 |
| 590 | * console.log( matches[ 0 ].getType() ); // 'url' |
| 591 | * console.log( matches[ 0 ].getUrl() ); // 'google.com' |
| 592 | * console.log( matches[ 1 ].getType() ); // 'email' |
| 593 | * console.log( matches[ 1 ].getEmail() ); // '[email protected]' |
| 594 | * |
| 595 | * @param {String} textOrHtml The HTML or text to find matches within |
| 596 | * (depending on if the {@link #urls}, {@link #email}, {@link #phone}, |
| 597 | * {@link #hashtag}, and {@link #mention} options are enabled). |
| 598 | * @return {Autolinker.match.Match[]} The array of Matches found in the |
| 599 | * given input `textOrHtml`. |
| 600 | */ |
| 601 | parse : function( textOrHtml ) { |
| 602 | var htmlParser = this.getHtmlParser(), |
| 603 | htmlNodes = htmlParser.parse( textOrHtml ), |
| 604 | anchorTagStackCount = 0, // used to only process text around anchor tags, and any inner text/html they may have; |
| 605 | matches = []; |
| 606 | |
| 607 | // Find all matches within the `textOrHtml` (but not matches that are |
| 608 | // already nested within <a>, <style> and <script> tags) |
| 609 | for( var i = 0, len = htmlNodes.length; i < len; i++ ) { |
| 610 | var node = htmlNodes[ i ], |
| 611 | nodeType = node.getType(); |
| 612 | |
| 613 | 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 |
| 614 | if( !node.isClosing() ) { // it's the start <a>, <style> or <script> tag |
| 615 | anchorTagStackCount++; |
| 616 | } else { // it's the end </a>, </style> or </script> tag |
| 617 | anchorTagStackCount = Math.max( anchorTagStackCount - 1, 0 ); // attempt to handle extraneous </a> tags by making sure the stack count never goes below 0 |
| 618 | } |
| 619 | |
| 620 | } else if( nodeType === 'text' && anchorTagStackCount === 0 ) { // Process text nodes that are not within an <a>, <style> and <script> tag |
| 621 | var textNodeMatches = this.parseText( node.getText(), node.getOffset() ); |
| 622 | |
| 623 | matches.push.apply( matches, textNodeMatches ); |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | |
| 628 | // After we have found all matches, remove subsequent matches that |
| 629 | // overlap with a previous match. This can happen for instance with URLs, |
| 630 | // where the url 'google.com/#link' would match '#link' as a hashtag. |
| 631 | matches = this.compactMatches( matches ); |
| 632 | |
| 633 | // And finally, remove matches for match types that have been turned |
| 634 | // off. We needed to have all match types turned on initially so that |
| 635 | // things like hashtags could be filtered out if they were really just |
| 636 | // part of a URL match (for instance, as a named anchor). |
| 637 | matches = this.removeUnwantedMatches( matches ); |
| 638 | |
| 639 | return matches; |
| 640 | }, |
| 641 | |
| 642 | |
| 643 | /** |
| 644 | * After we have found all matches, we need to remove subsequent matches |
| 645 | * that overlap with a previous match. This can happen for instance with |
| 646 | * URLs, where the url 'google.com/#link' would match '#link' as a hashtag. |
| 647 | * |
| 648 | * @private |
| 649 | * @param {Autolinker.match.Match[]} matches |
| 650 | * @return {Autolinker.match.Match[]} |
| 651 | */ |
| 652 | compactMatches : function( matches ) { |
| 653 | // First, the matches need to be sorted in order of offset |
| 654 | matches.sort( function( a, b ) { return a.getOffset() - b.getOffset(); } ); |
| 655 | |
| 656 | for( var i = 0; i < matches.length - 1; i++ ) { |
| 657 | var match = matches[ i ], |
| 658 | offset = match.getOffset(), |
| 659 | matchedTextLength = match.getMatchedText().length, |
| 660 | endIdx = offset + matchedTextLength; |
| 661 | |
| 662 | if( i + 1 < matches.length ) { |
| 663 | // Remove subsequent matches that equal offset with current match |
| 664 | if( matches[ i + 1 ].getOffset() === offset ) { |
| 665 | var removeIdx = matches[ i + 1 ].getMatchedText().length > matchedTextLength ? i : i + 1; |
| 666 | matches.splice( removeIdx, 1 ); |
| 667 | continue; |
| 668 | } |
| 669 | |
| 670 | // Remove subsequent matches that overlap with the current match |
| 671 | if( matches[ i + 1 ].getOffset() < endIdx ) { |
| 672 | matches.splice( i + 1, 1 ); |
| 673 | } |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | return matches; |
| 678 | }, |
| 679 | |
| 680 | |
| 681 | /** |
| 682 | * Removes matches for matchers that were turned off in the options. For |
| 683 | * example, if {@link #hashtag hashtags} were not to be matched, we'll |
| 684 | * remove them from the `matches` array here. |
| 685 | * |
| 686 | * @private |
| 687 | * @param {Autolinker.match.Match[]} matches The array of matches to remove |
| 688 | * the unwanted matches from. Note: this array is mutated for the |
| 689 | * removals. |
| 690 | * @return {Autolinker.match.Match[]} The mutated input `matches` array. |
| 691 | */ |
| 692 | removeUnwantedMatches : function( matches ) { |
| 693 | var remove = Autolinker.Util.remove; |
| 694 | |
| 695 | if( !this.hashtag ) remove( matches, function( match ) { return match.getType() === 'hashtag'; } ); |
| 696 | if( !this.email ) remove( matches, function( match ) { return match.getType() === 'email'; } ); |
| 697 | if( !this.phone ) remove( matches, function( match ) { return match.getType() === 'phone'; } ); |
| 698 | if( !this.mention ) remove( matches, function( match ) { return match.getType() === 'mention'; } ); |
| 699 | if( !this.urls.schemeMatches ) { |
| 700 | remove( matches, function( m ) { return m.getType() === 'url' && m.getUrlMatchType() === 'scheme'; } ); |
| 701 | } |
| 702 | if( !this.urls.wwwMatches ) { |
| 703 | remove( matches, function( m ) { return m.getType() === 'url' && m.getUrlMatchType() === 'www'; } ); |
| 704 | } |
| 705 | if( !this.urls.tldMatches ) { |
| 706 | remove( matches, function( m ) { return m.getType() === 'url' && m.getUrlMatchType() === 'tld'; } ); |
| 707 | } |
| 708 | |
| 709 | return matches; |
| 710 | }, |
| 711 | |
| 712 | |
| 713 | /** |
| 714 | * Parses the input `text` looking for URLs, email addresses, phone |
| 715 | * numbers, username handles, and hashtags (depending on the configuration |
| 716 | * of the Autolinker instance), and returns an array of {@link Autolinker.match.Match} |
| 717 | * objects describing those matches. |
| 718 | * |
| 719 | * This method processes a **non-HTML string**, and is used to parse and |
| 720 | * match within the text nodes of an HTML string. This method is used |
| 721 | * internally by {@link #parse}. |
| 722 | * |
| 723 | * @private |
| 724 | * @param {String} text The text to find matches within (depending on if the |
| 725 | * {@link #urls}, {@link #email}, {@link #phone}, |
| 726 | * {@link #hashtag}, and {@link #mention} options are enabled). This must be a non-HTML string. |
| 727 | * @param {Number} [offset=0] The offset of the text node within the |
| 728 | * original string. This is used when parsing with the {@link #parse} |
| 729 | * method to generate correct offsets within the {@link Autolinker.match.Match} |
| 730 | * instances, but may be omitted if calling this method publicly. |
| 731 | * @return {Autolinker.match.Match[]} The array of Matches found in the |
| 732 | * given input `text`. |
| 733 | */ |
| 734 | parseText : function( text, offset ) { |
| 735 | offset = offset || 0; |
| 736 | var matchers = this.getMatchers(), |
| 737 | matches = []; |
| 738 | |
| 739 | for( var i = 0, numMatchers = matchers.length; i < numMatchers; i++ ) { |
| 740 | var textMatches = matchers[ i ].parseMatches( text ); |
| 741 | |
| 742 | // Correct the offset of each of the matches. They are originally |
| 743 | // the offset of the match within the provided text node, but we |
| 744 | // need to correct them to be relative to the original HTML input |
| 745 | // string (i.e. the one provided to #parse). |
| 746 | for( var j = 0, numTextMatches = textMatches.length; j < numTextMatches; j++ ) { |
| 747 | textMatches[ j ].setOffset( offset + textMatches[ j ].getOffset() ); |
| 748 | } |
| 749 | |
| 750 | matches.push.apply( matches, textMatches ); |
| 751 | } |
| 752 | return matches; |
| 753 | }, |
| 754 | |
| 755 | |
| 756 | /** |
| 757 | * Automatically links URLs, Email addresses, Phone numbers, Hashtags, |
| 758 | * and Mentions (Twitter, Instagram, Soundcloud) found in the given chunk of HTML. Does not link |
| 759 | * URLs found within HTML tags. |
| 760 | * |
| 761 | * For instance, if given the text: `You should go to http://www.yahoo.com`, |
| 762 | * then the result will be `You should go to |
| 763 | * <a href="http://www.yahoo.com">http://www.yahoo.com</a>` |
| 764 | * |
| 765 | * This method finds the text around any HTML elements in the input |
| 766 | * `textOrHtml`, which will be the text that is processed. Any original HTML |
| 767 | * elements will be left as-is, as well as the text that is already wrapped |
| 768 | * in anchor (<a>) tags. |
| 769 | * |
| 770 | * @param {String} textOrHtml The HTML or text to autolink matches within |
| 771 | * (depending on if the {@link #urls}, {@link #email}, {@link #phone}, {@link #hashtag}, and {@link #mention} options are enabled). |
| 772 | * @return {String} The HTML, with matches automatically linked. |
| 773 | */ |
| 774 | link : function( textOrHtml ) { |
| 775 | if( !textOrHtml ) { return ""; } // handle `null` and `undefined` |
| 776 | |
| 777 | var matches = this.parse( textOrHtml ), |
| 778 | newHtml = [], |
| 779 | lastIndex = 0; |
| 780 | |
| 781 | for( var i = 0, len = matches.length; i < len; i++ ) { |
| 782 | var match = matches[ i ]; |
| 783 | |
| 784 | newHtml.push( textOrHtml.substring( lastIndex, match.getOffset() ) ); |
| 785 | newHtml.push( this.createMatchReturnVal( match ) ); |
| 786 | |
| 787 | lastIndex = match.getOffset() + match.getMatchedText().length; |
| 788 | } |
| 789 | newHtml.push( textOrHtml.substring( lastIndex ) ); // handle the text after the last match |
| 790 | |
| 791 | return newHtml.join( '' ); |
| 792 | }, |
| 793 | |
| 794 | |
| 795 | /** |
| 796 | * Creates the return string value for a given match in the input string. |
| 797 | * |
| 798 | * This method handles the {@link #replaceFn}, if one was provided. |
| 799 | * |
| 800 | * @private |
| 801 | * @param {Autolinker.match.Match} match The Match object that represents |
| 802 | * the match. |
| 803 | * @return {String} The string that the `match` should be replaced with. |
| 804 | * This is usually the anchor tag string, but may be the `matchStr` itself |
| 805 | * if the match is not to be replaced. |
| 806 | */ |
| 807 | createMatchReturnVal : function( match ) { |
| 808 | // Handle a custom `replaceFn` being provided |
| 809 | var replaceFnResult; |
| 810 | if( this.replaceFn ) { |
| 811 | replaceFnResult = this.replaceFn.call( this.context, match ); // Autolinker instance is the context |
| 812 | } |
| 813 | |
| 814 | if( typeof replaceFnResult === 'string' ) { |
| 815 | return replaceFnResult; // `replaceFn` returned a string, use that |
| 816 | |
| 817 | } else if( replaceFnResult === false ) { |
| 818 | return match.getMatchedText(); // no replacement for the match |
| 819 | |
| 820 | } else if( replaceFnResult instanceof Autolinker.HtmlTag ) { |
| 821 | return replaceFnResult.toAnchorString(); |
| 822 | |
| 823 | } else { // replaceFnResult === true, or no/unknown return value from function |
| 824 | // Perform Autolinker's default anchor tag generation |
| 825 | var anchorTag = match.buildTag(); // returns an Autolinker.HtmlTag instance |
| 826 | |
| 827 | return anchorTag.toAnchorString(); |
| 828 | } |
| 829 | }, |
| 830 | |
| 831 | |
| 832 | /** |
| 833 | * Lazily instantiates and returns the {@link #htmlParser} instance for this |
| 834 | * Autolinker instance. |
| 835 | * |
| 836 | * @protected |
| 837 | * @return {Autolinker.htmlParser.HtmlParser} |
| 838 | */ |
| 839 | getHtmlParser : function() { |
| 840 | var htmlParser = this.htmlParser; |
| 841 | |
| 842 | if( !htmlParser ) { |
| 843 | htmlParser = this.htmlParser = new Autolinker.htmlParser.HtmlParser(); |
| 844 | } |
| 845 | |
| 846 | return htmlParser; |
| 847 | }, |
| 848 | |
| 849 | |
| 850 | /** |
| 851 | * Lazily instantiates and returns the {@link Autolinker.matcher.Matcher} |
| 852 | * instances for this Autolinker instance. |
| 853 | * |
| 854 | * @protected |
| 855 | * @return {Autolinker.matcher.Matcher[]} |
| 856 | */ |
| 857 | getMatchers : function() { |
| 858 | if( !this.matchers ) { |
| 859 | var matchersNs = Autolinker.matcher, |
| 860 | tagBuilder = this.getTagBuilder(); |
| 861 | |
| 862 | var matchers = [ |
| 863 | new matchersNs.Hashtag( { tagBuilder: tagBuilder, serviceName: this.hashtag } ), |
| 864 | new matchersNs.Email( { tagBuilder: tagBuilder } ), |
| 865 | new matchersNs.Phone( { tagBuilder: tagBuilder } ), |
| 866 | new matchersNs.Mention( { tagBuilder: tagBuilder, serviceName: this.mention } ), |
| 867 | new matchersNs.Url( { tagBuilder: tagBuilder, stripPrefix: this.stripPrefix, stripTrailingSlash: this.stripTrailingSlash, decodePercentEncoding: this.decodePercentEncoding } ) |
| 868 | ]; |
| 869 | |
| 870 | return ( this.matchers = matchers ); |
| 871 | |
| 872 | } else { |
| 873 | return this.matchers; |
| 874 | } |
| 875 | }, |
| 876 | |
| 877 | |
| 878 | /** |
| 879 | * Returns the {@link #tagBuilder} instance for this Autolinker instance, lazily instantiating it |
| 880 | * if it does not yet exist. |
| 881 | * |
| 882 | * This method may be used in a {@link #replaceFn} to generate the {@link Autolinker.HtmlTag HtmlTag} instance that |
| 883 | * Autolinker would normally generate, and then allow for modifications before returning it. For example: |
| 884 | * |
| 885 | * var html = Autolinker.link( "Test google.com", { |
| 886 | * replaceFn : function( match ) { |
| 887 | * var tag = match.buildTag(); // returns an {@link Autolinker.HtmlTag} instance |
| 888 | * tag.setAttr( 'rel', 'nofollow' ); |
| 889 | * |
| 890 | * return tag; |
| 891 | * } |
| 892 | * } ); |
| 893 | * |
| 894 | * // generated html: |
| 895 | * // Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a> |
| 896 | * |
| 897 | * @return {Autolinker.AnchorTagBuilder} |
| 898 | */ |
| 899 | getTagBuilder : function() { |
| 900 | var tagBuilder = this.tagBuilder; |
| 901 | |
| 902 | if( !tagBuilder ) { |
| 903 | tagBuilder = this.tagBuilder = new Autolinker.AnchorTagBuilder( { |
| 904 | newWindow : this.newWindow, |
| 905 | truncate : this.truncate, |
| 906 | className : this.className |
| 907 | } ); |
| 908 | } |
| 909 | |
| 910 | return tagBuilder; |
| 911 | } |
| 912 | |
| 913 | }; |
| 914 | |
| 915 | |
| 916 | // Autolinker Namespaces |
| 917 | |
| 918 | Autolinker.match = {}; |
| 919 | Autolinker.matcher = {}; |
| 920 | Autolinker.htmlParser = {}; |
| 921 | Autolinker.truncate = {}; |