1/* eslint-env amd */ 2/* globals module:false */ 3 4// https://github.com/umdjs/umd/blob/master/templates/returnExports.js 5(function (root, factory) { 6 'use strict'; 7 8 if (typeof define === 'function' && define.amd) { 9 // AMD. Register as an anonymous module. 10 define([], factory); 11 } else if (typeof module === 'object' && module.exports) { 12 // Node. Does not work with strict CommonJS, but 13 // only CommonJS-like environments that support module.exports, 14 // like Node. 15 module.exports = factory(); 16 } else { 17 // Browser globals (root is window) 18 root.AnchorJS = factory(); 19 root.anchors = new root.AnchorJS(); 20 } 21}(this, function () { 22 'use strict'; 23 24 function AnchorJS(options) { 25 this.options = options || {}; 26 this.elements = []; 27 28 /** 29 * Assigns options to the internal options object, and provides defaults. 30 * @param {Object} opts - Options object 31 */ 32 function _applyRemainingDefaultOptions(opts) { 33 opts.icon = opts.hasOwnProperty('icon') ? opts.icon : '\ue9cb'; // Accepts characters (and also URLs?), like '#', '¶', 'â¡', or '§'. 34 opts.visible = opts.hasOwnProperty('visible') ? opts.visible : 'hover'; // Also accepts 'always' & 'touch' 35 opts.placement = opts.hasOwnProperty('placement') ? opts.placement : 'right'; // Also accepts 'left' 36 opts.ariaLabel = opts.hasOwnProperty('ariaLabel') ? opts.ariaLabel : 'Anchor'; // Accepts any text. 37 opts.class = opts.hasOwnProperty('class') ? opts.class : ''; // Accepts any class name. 38 opts.base = opts.hasOwnProperty('base') ? opts.base : ''; // Accepts any base URI. 39 // Using Math.floor here will ensure the value is Number-cast and an integer. 40 opts.truncate = opts.hasOwnProperty('truncate') ? Math.floor(opts.truncate) : 64; // Accepts any value that can be typecast to a number. 41 opts.titleText = opts.hasOwnProperty('titleText') ? opts.titleText : ''; // Accepts any text. 42 } 43 44 _applyRemainingDefaultOptions(this.options); 45 46 /** 47 * Checks to see if this device supports touch. Uses criteria pulled from Modernizr: 48 * https://github.com/Modernizr/Modernizr/blob/da22eb27631fc4957f67607fe6042e85c0a84656/feature-detects/touchevents.js#L40 49 * @return {Boolean} - true if the current device supports touch. 50 */ 51 this.isTouchDevice = function() { 52 return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch); 53 }; 54 55 /** 56 * Add anchor links to page elements. 57 * @param {String|Array|Nodelist} selector - A CSS selector for targeting the elements you wish to add anchor links 58 * to. Also accepts an array or nodeList containing the relavant elements. 59 * @return {this} - The AnchorJS object 60 */ 61 this.add = function(selector) { 62 var elements, 63 elsWithIds, 64 idList, 65 elementID, 66 i, 67 index, 68 count, 69 tidyText, 70 newTidyText, 71 anchor, 72 visibleOptionToUse, 73 hrefBase, 74 indexesToDrop = []; 75 76 // We reapply options here because somebody may have overwritten the default options object when setting options. 77 // For example, this overwrites all options but visible: 78 // 79 // anchors.options = { visible: 'always'; } 80 _applyRemainingDefaultOptions(this.options); 81 82 visibleOptionToUse = this.options.visible; 83 if (visibleOptionToUse === 'touch') { 84 visibleOptionToUse = this.isTouchDevice() ? 'always' : 'hover'; 85 } 86 87 // Provide a sensible default selector, if none is given. 88 if (!selector) { 89 selector = 'h2, h3, h4, h5, h6'; 90 } 91 92 elements = _getElements(selector); 93 94 if (elements.length === 0) { 95 return this; 96 } 97 98 _addBaselineStyles(); 99 100 // We produce a list of existing IDs so we don't generate a duplicate. 101 elsWithIds = document.querySelectorAll('[id]'); 102 idList = [].map.call(elsWithIds, function assign(el) { 103 return el.id; 104 }); 105 106 for (i = 0; i < elements.length; i++) { 107 if (this.hasAnchorJSLink(elements[i])) { 108 indexesToDrop.push(i); 109 continue; 110 } 111 112 if (elements[i].hasAttribute('id')) { 113 elementID = elements[i].getAttribute('id'); 114 } else if (elements[i].hasAttribute('data-anchor-id')) { 115 elementID = elements[i].getAttribute('data-anchor-id'); 116 } else { 117 tidyText = this.urlify(elements[i].textContent); 118 119 // Compare our generated ID to existing IDs (and increment it if needed) 120 // before we add it to the page. 121 newTidyText = tidyText; 122 count = 0; 123 do { 124 if (index !== undefined) { 125 newTidyText = tidyText + '-' + count; 126 } 127 128 index = idList.indexOf(newTidyText); 129 count += 1; 130 } while (index !== -1); 131 index = undefined; 132 idList.push(newTidyText); 133 134 elements[i].setAttribute('id', newTidyText); 135 elementID = newTidyText; 136 } 137 138 // The following code efficiently builds this DOM structure: 139 // `<a class="anchorjs-link ${this.options.class}" 140 // aria-label="${this.options.ariaLabel}" 141 // data-anchorjs-icon="${this.options.icon}" 142 // title="${this.options.titleText}" 143 // href="this.options.base#${elementID}"> 144 // </a>;` 145 anchor = document.createElement('a'); 146 anchor.className = 'anchorjs-link ' + this.options.class; 147 anchor.setAttribute('aria-label', this.options.ariaLabel); 148 anchor.setAttribute('data-anchorjs-icon', this.options.icon); 149 if (this.options.titleText) { 150 anchor.title = this.options.titleText; 151 } 152 // Adjust the href if there's a <base>
152 tag. See https://github.com/bryanbraun/anchorjs/issues/98 153 hrefBase = document.querySelector('base') ? window.location.pathname + window.location.search : ''; 154 hrefBase = this.options.base || hrefBase; 155 anchor.href = hrefBase + '#' + elementID; 156 157 if (visibleOptionToUse === 'always') { 158 anchor.style.opacity = '1'; 159 } 160 161 if (this.options.icon === '\ue9cb') { 162 anchor.style.font = '1em/1 anchorjs-icons'; 163 164 // We set lineHeight = 1 here because the `anchorjs-icons` font family could otherwise affect the 165 // height of the heading. This isn't the case for icons with `placement: left`, so we restore 166 // line-height: inherit in that case, ensuring they remain positioned correctly. For more info, 167 // see https://github.com/bryanbraun/anchorjs/issues/39. 168 if (this.options.placement === 'left') { 169 anchor.style.lineHeight = 'inherit'; 170 } 171 } 172 173 if (this.options.placement === 'left') { 174 anchor.style.position = 'absolute'; 175 anchor.style.marginLeft = '-1em'; 176 anchor.style.paddingRight = '0.5em'; 177 elements[i].insertBefore(anchor, elements[i].firstChild); 178 } else { // if the option provided is `right` (or anything else). 179 anchor.style.paddingLeft = '0.375em'; 180 elements[i].appendChild(anchor); 181 } 182 } 183 184 for (i = 0; i < indexesToDrop.length; i++) { 185 elements.splice(indexesToDrop[i] - i, 1); 186 } 187 this.elements = this.elements.concat(elements); 188 189 return this; 190 }; 191 192 /** 193 * Removes all anchorjs-links from elements targeted by the selector. 194 * @param {String|Array|Nodelist} selector - A CSS selector string targeting elements with anchor links, 195 * OR a nodeList / array containing the DOM elements. 196 * @return {this} - The AnchorJS object 197 */ 198 this.remove = function(selector) { 199 var index, 200 domAnchor, 201 elements = _getElements(selector); 202 203 for (var i = 0; i < elements.length; i++) { 204 domAnchor = elements[i].querySelector('.anchorjs-link'); 205 if (domAnchor) { 206 // Drop the element from our main list, if it's in there. 207 index = this.elements.indexOf(elements[i]); 208 if (index !== -1) { 209 this.elements.splice(index, 1); 210 } 211 // Remove the anchor from the DOM. 212 elements[i].removeChild(domAnchor); 213 } 214 } 215 return this; 216 }; 217 218 /** 219 * Removes all anchorjs links. Mostly used for tests. 220 */ 221 this.removeAll = function() { 222 this.remove(this.elements); 223 }; 224 225 /** 226 * Urlify - Refine text so it makes a good ID. 227 * 228 * To do this, we remove apostrophes, replace non-safe characters with hyphens, 229 * remove extra hyphens, truncate, trim hyphens, and make lowercase. 230 * 231 * @param {String} text - Any text. Usually pulled from the webpage element we are linking to. 232 * @return {String} - hyphen-delimited text for use in IDs and URLs. 233 */ 234 this.urlify = function(text) { 235 // Regex for finding the non-safe URL characters (many need escaping): & +$,:;=?@"#{}|^~[`%!'<>]./()*\ (newlines, tabs, backspace, & vertical tabs) 236 var nonsafeChars = /[& +$,:;=?@"#{}|^~[`%!'<>\]\.\/\(\)\*\\\n\t\b\v]/g, 237 urlText; 238 239 // The reason we include this _applyRemainingDefaultOptions is so urlify can be called independently, 240 // even after setting options. This can be useful for tests or other applications. 241 if (!this.options.truncate) { 242 _applyRemainingDefaultOptions(this.options); 243 } 244 245 // Note: we trim hyphens after truncating because truncating can cause dangling hyphens. 246 // Example string: // " â¡â¡ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." 247 urlText = text.trim() // "â¡â¡ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." 248 .replace(/\'/gi, '') // "â¡â¡ Dont forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." 249 .replace(nonsafeChars, '-') // "â¡â¡-Dont-forget--URL-fragments-should-be-i18n-friendly--hyphenated--short--and-clean-" 250 .replace(/-{2,}/g, '-') // "â¡â¡-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-s
250hort-and-clean-" 251 .substring(0, this.options.truncate) // "â¡â¡-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-" 252 .replace(/^-+|-+$/gm, '') // "â¡â¡-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated" 253 .toLowerCase(); // "â¡â¡-dont-forget-url-fragments-should-be-i18n-friendly-hyphenated" 254 255 return urlText; 256 }; 257 258 /** 259 * Determines if this element already has an AnchorJS link on it. 260 * Uses this technique: http://stackoverflow.com/a/5898748/1154642 261 * @param {HTMLElement} el - a DOM node 262 * @return {Boolean} true/false 263 */ 264 this.hasAnchorJSLink = function(el) { 265 var hasLeftAnchor = el.firstChild && ((' ' + el.firstChild.className + ' ').indexOf(' anchorjs-link ') > -1), 266 hasRightAnchor = el.lastChild && ((' ' + el.lastChild.className + ' ').indexOf(' anchorjs-link ') > -1); 267 268 return hasLeftAnchor || hasRightAnchor || false; 269 }; 270 271 /** 272 * Turns a selector, nodeList, or array of elements into an array of elements (so we can use array methods). 273 * It also throws errors on any other inputs. Used to handle inputs to .add and .remove. 274 * @param {String|Array|Nodelist} input - A CSS selector string targeting elements with anchor links, 275 * OR a nodeList / array containing the DOM elements. 276 * @return {Array} - An array containing the elements we want. 277 */ 278 function _getElements(input) { 279 var elements; 280 if (typeof input === 'string' || input instanceof String) { 281 // See https://davidwalsh.name/nodelist-array for the technique transforming nodeList -> Array. 282 elements = [].slice.call(document.querySelectorAll(input)); 283 // I checked the 'input instanceof NodeList' test in IE9 and modern browsers and it worked for me. 284 } else if (Array.isArray(input) || input instanceof NodeList) { 285 elements = [].slice.call(input); 286 } else { 287 throw new Error('The selector provided to AnchorJS was invalid.'); 288 } 289 return elements; 290 } 291 292 /** 293 * _addBaselineStyles 294 * Adds baseline styles to the page, used by all AnchorJS links irregardless of configuration. 295 */ 296 function _addBaselineStyles() { 297 // We don't want to add global baseline styles if they've been added before. 298 if (document.head.querySelector('style.anchorjs') !== null) { 299 return; 300 } 301 302 var style = document.createElement('style'), 303 linkRule = 304 ' .anchorjs-link {' + 305 ' opacity: 0;' + 306 ' text-decoration: none;' + 307 ' -webkit-font-smoothing: antialiased;' + 308 ' -moz-osx-font-smoothing: grayscale;' + 309 ' }', 310 hoverRule = 311 ' *:hover > .anchorjs-link,' + 312 ' .anchorjs-link:focus {' + 313 ' opacity: 1;' + 314 ' }', 315 anchorjsLinkFontFace = 316 ' @font-face {' + 317 ' font-family: "anchorjs-icons";' + // Icon from icomoon; 10px wide & 10px tall; 2 empty below & 4 above 318 ' src: url(data:n/a;base64,AAEAAAALAIAAAwAwT1MvMg8yG2cAAAE4AAAAYGNtYXDp3gC3AAABpAAAAExnYXNwAAAAEAAAA9wAAAAIZ2x5ZlQCcfwAAAH4AAABCGhlYWQHFvHyAAAAvAAAADZoaGVhBnACFwAAAPQAAAAkaG10eASAADEAAAGYAAAADGxvY2EACACEAAAB8AAAAAhtYXhwAAYAVwAAARgAAAAgbmFtZQGOH9cAAAMAAAAAunBvc3QAAwAAAAADvAAAACAAAQAAAAEAAHzE2p9fDzz1AAkEAAAAAADRecUWAAAAANQA6R8AAAAAAoACwAAAAAgAAgAAAAAAAAABAAADwP/AAAACgAAA/9MCrQABAAAAAAAAAAAAAAAAAAAAAwABAAAAAwBVAAIAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMCQAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAg//0DwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAAIAAAACgAAxAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADAAAAAIAAgAAgAAACDpy//9//8AAAAg6cv//f///+EWNwADAAEAAAAAAAAAAAAAAAAACACEAAEAAAAAAAAAAAAAAAAxAAACAAQARAKAAsAAKwBUAAABIiYnJjQ3NzY2MzIWFxYUBwcGIicmNDc3NjQnJiYjIgYHBwYUFxYUBwYGIwciJicmNDc3NjIXFhQHBwYUFxYWMzI2Nzc2NCcmNDc2MhcWFAcHBgYjARQGDAUtLXoWOR8fORYtLTgKGwoKCjgaGg0gEhIgDXoaGgkJBQwHdR85Fi0tOAobCgoKOBoaDSASEiANehoaCQkKGwotLXoWOR8BMwUFLYEuehYXFxYugC44CQkKGwo4GkoaDQ0NDXoaShoKGwoFBe8XFi6ALjgJCQobCjgaShoNDQ0NehpKGgobCgoKLYEuehYXAAAADACWAAEAAAAAAAEACAAAAAEAAAAAAAIAAwAIAAEAAAAAAAMACAAAAAEAAAAAAAQACAAAAAEAAAAAAAUAAQALAAEAAAAAAAYACAAAAAMAAQQJAAEAEAAMAAMAAQQJAAIABgAcAAMAAQQJAAMAEAAMAAMAAQQJAAQAEAAMAAMAAQQJAAUAAgAiAAMAAQQJAAYAEAAMYW5jaG9yanM0MDBAAGEAbgBjAGgAbwByAGoAcwA0ADAAMABAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAP) format("truetype");' + 319 ' }', 320 pseudoElContent = 321 ' [data-anchorjs-icon]::after {' + 322 ' content: attr(data-anchorjs-icon);' + 323 ' }', 324 firstStyleEl; 325 326 style.className = 'anchorjs'; 327 style.appendChild(document.createTextNode('')); // Necessary for Webkit. 328 329 // We place it in the head with the other style tags, if possible, so as to 330 // not look out of place. We insert before the others so these styles can be 331 // overridden if necessary. 332 firstStyleEl = document.head.querySelector('[rel="stylesheet"], style'); 333 if (firstStyleEl === undefined) { 334 document.head.appendChild(style); 335 } else { 336 document.head.insertBefore(style, firstStyleEl); 337 } 338 339 style.sheet.insertRule(linkRule, style.sheet.cssRules.length); 340 style.sheet.insertRule(hoverRule, style.sheet.cssRules.length); 341 style.sheet.insertRule(pseudoElContent, style.sheet.cssRules.length); 342 style.sheet.insertRule(anchorjsLinkFontFace, style.sheet.cssRules.length); 343 } 344 } 345 346 return AnchorJS; 347}));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.