diff --git a/rakelib/build.rake b/rakelib/build.rake index 76c79ad24f..f729ff14c9 100644 --- a/rakelib/build.rake +++ b/rakelib/build.rake @@ -1,5 +1,6 @@ require 'rake/clean' require 'yaml' +require 'nokogiri' CLEAN.include('build') CLEAN.include('resources') @@ -37,7 +38,53 @@ task :check_for_title do end end +desc 'Add anchor tag to all the headers' +task :header_anchors do + begin + Dir["public/**/*.html"].select {|file| + html = Nokogiri::HTML(open(file)) + puts "Parsing file: " + file.pathmap + html.css('h1,h2,h3,h4,h5,h6').each {|header| + if header['id'] == nil || header['id'].exclude?('searchResultTitle') + id = header['id'] || generate_id(header.text) + i = Nokogiri::XML::Node.new "i", html + i['class'] = "fa fa-link" + i['aria-hidden'] = "true" + + a = Nokogiri::XML::Node.new "a", html + a['href'] = '#' + id + a['class'] = "header-anchor" + a.content = "a" + + i.parent = a + header.children.first.add_previous_sibling(a) + end + } + File.write(file, html.to_html) + } + puts 'Successfully created header anchors!!!' + rescue Exception => e + puts 'Failed: Error while generating header anchors!!!' + e.message + puts e.backtrace + end +end + desc "build the documentation" -task :compile => [:clean, :init, :check_for_title, :run_hugo] +task :compile => [:clean, :init, :check_for_title, :run_hugo, :header_anchors] task :build => [:compile, "static_checks:all"] +private_methods + +def generate_id text + downcase = text.strip.downcase + id_with_spaces = downcase.gsub! /[^a-zA-z0-9_]+/, ' ' + if id_with_spaces === nil + return downcase + end + id_with_spaces = id_with_spaces.strip + id = id_with_spaces.gsub! /[ ]+/, '-' + if id === nil + return id_with_spaces + end + id +end diff --git a/themes/hugo-book/assets/book.scss b/themes/hugo-book/assets/book.scss index 2e098a4ce7..4010b1ed64 100644 --- a/themes/hugo-book/assets/book.scss +++ b/themes/hugo-book/assets/book.scss @@ -369,3 +369,36 @@ a.navigation { font-weight: 600; font-size: 22px; } + +a.header-anchor { + display: none; + margin-left: -15px; + cursor: pointer; + position: absolute; + top: 20px; + left: 0; + bottom: 0; +} + +h2, h3 { + a.header-anchor { + margin-left: -10px; + } +} + +h4, h5, h6 { + a.header-anchor { + margin-left: -8px; + top: 0; + } +} + +h1, h2, h3, h4, h5, h6 { + position: relative; +} + +h1:hover, h2:hover, h3:hover, h4:hover, h5:hover, h6:hover { + a.header-anchor { + display: inline-block; + } +} diff --git a/yarn.lock b/yarn.lock index 566cfc0c37..39be95add5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1032,7 +1032,7 @@ lru-cache@^4.0.1: pseudomap "^1.0.2" yallist "^2.1.2" -lunr@^2.3.5: +lunr@2.3.6: version "2.3.6" resolved "https://registry.yarnpkg.com/lunr/-/lunr-2.3.6.tgz#f278beee7ffd56ad86e6e478ce02ab2b98c78dd5" integrity sha512-swStvEyDqQ85MGpABCMBclZcLI/pBIlu8FFDtmX197+oEgKloJ67QnB+Tidh0340HmLMs39c4GrkPY3cmkXp6Q==