Browse Source

Replace the header_links plugin with client-side generated anchors. (#4165)

* Replace the header_links plugin with client-side generated anchors.

Fixes facebook/react#4124

* Move anchor-link code into a separate script

Also adds a couple comments, for context.
main
Bryan Braun 8 years ago
committed by Kevin Lacker
parent
commit
eabdc7bdeb
  1. 30
      _js/anchor-links.js
  2. 1
      _layouts/default.html
  3. 20
      _plugins/header_links.rb
  4. 1
      css/react.scss

30
_js/anchor-links.js

@ -0,0 +1,30 @@
// Add anchors to headings client-side, which prevents them from showing up
// in RSS feeds. See https://github.com/facebook/react/issues/4124.
(function() {
var selector = '.inner-content h2, .inner-content h3, .inner-content h4';
var elements = document.querySelectorAll(selector);
for (var i = 0; i < elements.length; i++) {
var textMethod = document.body.textContent ? "textContent" : "innerText";
var roughText = elements[i][textMethod];
// Regex rule for making the title URL-friendly.
var urlFriendlyText = roughText.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^A-Za-z0-9\-_.\p{Cyrillic}\p{Hangul}\p{Hiragana}\p{Katakana}\p{Han}]/g, '');
// Create the anchor we'll jump to.
var anchor = document.createElement('a');
anchor.className = 'anchor';
anchor.name = urlFriendlyText;
elements[i].insertBefore(anchor, elements[i].firstChild);
// Create the clickable "#" icon.
var hashLink = document.createElement('a');
var icon = document.createTextNode("#");
hashLink.appendChild(icon);
hashLink.className = 'hash-link';
hashLink.href = '#' + urlFriendlyText;
elements[i].appendChild(hashLink);
}
}());

1
_layouts/default.html

@ -61,6 +61,7 @@
</div>
<div id="fb-root"></div>
<script src="/react/js/anchor-links.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

20
_plugins/header_links.rb

@ -1,20 +0,0 @@
require 'redcarpet'
require 'sanitize'
# Simple converter that is probably better than RedCarpet's built in TOC id
# generator (which ends up with things like id="toc_1"... terrible).
class Redcarpet::Render::HTML
def header(title, level)
# \p{Common} does not seem to include some of the Japanese alphabets and also includes
# some undesired characters like colon and parentheses, so we have to write out the
# necessary Unicode scripts individually.
clean_title = Sanitize.clean(title)
.downcase
.gsub(/\s+/, "-")
.gsub(/[^A-Za-z0-9\-_.\p{Cyrillic}\p{Hangul}\p{Hiragana}\p{Katakana}\p{Han}]/, "")
return "<h#{level}><a class=\"anchor\" name=\"#{clean_title}\"></a>#{title} <a class=\"hash-link\" href=\"##{clean_title}\">#</a></h#{level}>"
end
end

1
css/react.scss

@ -122,6 +122,7 @@ h1, h2, h3, h4, h5, h6 {
.hash-link {
color: $mediumTextColor;
display: none;
padding-left: 8px;
}
// Main Nav

Loading…
Cancel
Save