Skip to content

Commit

Permalink
Merge pull request #52 from allejo/develop
Browse files Browse the repository at this point in the history
  • Loading branch information
allejo committed Nov 28, 2020
2 parents 6f23f19 + fc252c0 commit 7cf23b7
Show file tree
Hide file tree
Showing 8 changed files with 171 additions and 80 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ jobs:
with:
ruby-version: '2.5'

- uses: actions/setup-python@v2
with:
python-version: '3.8'

- name: Configure Jekyll
if: matrix.jekyll-versions != '(GitHub Pages)'
run: |
Expand Down
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,17 @@ This snippet is highly customizable. Here are the available parameters to change
| `ordered` | bool | false | when set to true, an ordered list will be outputted instead of an unordered list |
| `item_class` | string | '' | add custom class for each list item; has support for `%level%` placeholder, which is the current heading level |
| `submenu_class` | string | '' | add custom class(es) for each child group of headings; has support for `%level%` placeholder which is the current "submenu" heading level |
| `baseurl` | string | '' | add a base url to the TOC links for when your TOC is on another page than the actual content |
| `base_url` | string | '' | add a base url to the TOC links for when your TOC is on another page than the actual content |
| `anchor_class` | string | '' | add custom class(es) for each anchor element |
| `skipNoIDs` | bool | false | skip headers that do not have an `id` attribute |
| `skip_no_ids` | bool | false | skip headers that do not have an `id` attribute |

<sup>*</sup> This is a required parameter

### Deprecated Variables

- `baseurl` has been deprecated since 1.1.0, use `base_url` instead
- `skipNoIDs` has been deprecated since 1.1.0, use `skip_no_ids` instead

## Performance

The performance impact of this snippet on your site is pretty negligible. The stats below were gotten from Jekyll's `--profile` option.
Expand Down
148 changes: 80 additions & 68 deletions _includes/toc.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
OTHER DEALINGS IN THE SOFTWARE.
{% endcomment %}
{% comment %}
Version 1.0.14
Version 1.1.0
https://github.com/allejo/jekyll-toc

"...like all things liquid - where there's a will, and ~36 hours to spare, there's usually a/some way" ~jaybe
Expand All @@ -44,127 +44,139 @@
* ordered (bool) : false - when set to true, an ordered list will be outputted instead of an unordered list
* item_class (string) : '' - add custom class(es) for each list item; has support for '%level%' placeholder, which is the current heading level
* submenu_class (string) : '' - add custom class(es) for each child group of headings; has support for '%level%' placeholder which is the current "submenu" heading level
* baseurl (string) : '' - add a base url to the TOC links for when your TOC is on another page than the actual content
* base_url (string) : '' - add a base url to the TOC links for when your TOC is on another page than the actual content
* anchor_class (string) : '' - add custom class(es) for each anchor element
* skipNoIDs (bool) : false - skip headers that do not have an `id` attribute
* skip_no_ids (bool) : false - skip headers that do not have an `id` attribute

Output:
An ordered or unordered list representing the table of contents of a markdown block. This snippet will only
generate the table of contents and will NOT output the markdown given to it
{% endcomment %}

{% capture my_toc %}{% endcapture %}
{% capture newline %}
{% endcapture %}
{% assign newline = newline | rstrip %} <!-- Remove the extra spacing but preserve the newline -->

{% capture deprecation_warnings %}{% endcapture %}

{% if include.baseurl %}
{% capture deprecation_warnings %}{{ deprecation_warnings }}<!-- jekyll-toc :: "baseurl" has been deprecated, use "base_url" instead -->{{ newline }}{% endcapture %}
{% endif %}

{% if include.skipNoIDs %}
{% capture deprecation_warnings %}{{ deprecation_warnings }}<!-- jekyll-toc :: "skipNoIDs" has been deprecated, use "skip_no_ids" instead -->{{ newline }}{% endcapture %}
{% endif %}

{% capture jekyll_toc %}{% endcapture %}
{% assign orderedList = include.ordered | default: false %}
{% assign skipNoIDs = include.skipNoIDs | default: false %}
{% assign baseURL = include.base_url | default: include.baseurl | default: '' %}
{% assign skipNoIDs = include.skip_no_ids | default: include.skipNoIDs | default: false %}
{% assign minHeader = include.h_min | default: 1 %}
{% assign maxHeader = include.h_max | default: 6 %}
{% assign nodes = include.html | split: '<h' %}
{% assign nodes = include.html | strip | split: '<h' %}

{% assign firstHeader = true %}
{% assign previousLevel = 0 %}
{% assign currLevel = 0 %}
{% assign lastLevel = 0 %}

{% capture listModifier %}{% if orderedList %}1.{% else %}-{% endif %}{% endcapture %}
{% capture listModifier %}{% if orderedList %}ol{% else %}ul{% endif %}{% endcapture %}

{% for node in nodes %}
{% if node == "" %}
{% continue %}
{% endif %}

{% assign headerLevel = node | replace: '"', '' | slice: 0, 1 | times: 1 %}
{% assign currLevel = node | replace: '"', '' | slice: 0, 1 | times: 1 %}

{% if headerLevel < minHeader or headerLevel > maxHeader %}
{% if currLevel < minHeader or currLevel > maxHeader %}
{% continue %}
{% endif %}

{% assign _workspace = node | split: '</h' %}

{% assign _idWorkspace = _workspace[0] | split: 'id="' %}
{% assign _idWorkspace = _idWorkspace[1] | split: '"' %}
{% assign html_id = _idWorkspace[0] %}
{% assign htmlID = _idWorkspace[0] %}

{% assign _classWorkspace = _workspace[0] | split: 'class="' %}
{% assign _classWorkspace = _classWorkspace[1] | split: '"' %}
{% assign html_class = _classWorkspace[0] %}
{% assign htmlClass = _classWorkspace[0] %}

{% if html_class contains "no_toc" %}
{% if htmlClass contains "no_toc" %}
{% continue %}
{% endif %}

{% if firstHeader %}
{% assign firstHeader = false %}
{% assign minHeader = headerLevel %}
{% assign minHeader = currLevel %}
{% endif %}

{% capture _hAttrToStrip %}{{ _workspace[0] | split: '>' | first }}>{% endcapture %}
{% assign header = _workspace[0] | replace: _hAttrToStrip, '' %}

{% assign indentAmount = headerLevel | minus: minHeader %}
{% assign space = '' %}
{% for i in (1..indentAmount) %}
{% assign space = space | prepend: ' ' %}
{% endfor %}

{% if include.item_class and include.item_class != blank %}
{% capture listItemClass %}{:.{{ include.item_class | replace: '%level%', headerLevel }}}{% endcapture %}
{% capture listItemClass %} class="{{ include.item_class | replace: '%level%', currLevel | split: '.' | join: ' ' }}"{% endcapture %}
{% endif %}

{% if include.submenu_class and include.submenu_class != blank %}
{% assign subMenuLevel = currLevel | minus: 1 %}
{% capture subMenuClass %} class="{{ include.submenu_class | replace: '%level%', subMenuLevel | split: '.' | join: ' ' }}"{% endcapture %}
{% endif %}

{% capture anchor_body %}{% if include.sanitize %}{{ header | strip_html }}{% else %}{{ header }}{% endif %}{% endcapture %}
{% capture anchor_body %}{{ anchor_body | replace: "|", "\|" }}{% endcapture %}
{% capture anchorBody %}{% if include.sanitize %}{{ header | strip_html }}{% else %}{{ header }}{% endif %}{% endcapture %}

{% if htmlID %}
{% capture anchorAttributes %} href="{% if baseURL %}{{ baseURL }}{% endif %}#{{ htmlID }}"{% endcapture %}

{% if include.anchor_class %}
{% capture anchorAttributes %}{{ anchorAttributes }} class="{{ include.anchor_class | split: '.' | join: ' ' }}"{% endcapture %}
{% endif %}

{% if html_id %}
{% capture list_item %}[{{ anchor_body }}]({% if include.baseurl %}{{ include.baseurl }}{% endif %}#{{ html_id }}){% endcapture %}
{% capture listItem %}<a{{ anchorAttributes }}>{{ anchorBody }}</a>{% endcapture %}
{% elsif skipNoIDs == true %}
{% continue %}
{% else %}
{% capture list_item %}{{ anchor_body }}{% endcapture %}
{% capture listItem %}{{ anchorBody }}{% endcapture %}
{% endif %}

<!--
If we have a submenu class and we're unindenting, then we need to add a "closing" class to this group of bullet
points
-->
{% if include.submenu_class and previousLevel > indentAmount %}
<!--
`space` is the current indentation, so we if want to close off the previous grouping, we need to add one
more level of indentation
-->
{% assign submenuIndentation = space | prepend: ' ' %}

{% capture my_toc %}{{ my_toc }}
{{ submenuIndentation }}{:.{{ include.submenu_class | replace: '%level%', previousLevel }}}{% endcapture %}
{% if currLevel > lastLevel %}
{% capture jekyll_toc %}{{ jekyll_toc }}<{{ listModifier }}{{ subMenuClass }}>{% endcapture %}
{% elsif currLevel < lastLevel %}
{% assign repeatCount = lastLevel | minus: currLevel %}

{% for i in (1..repeatCount) %}
{% capture jekyll_toc %}{{ jekyll_toc }}</li></{{ listModifier }}>{% endcapture %}
{% endfor %}

{% capture jekyll_toc %}{{ jekyll_toc }}</li>{% endcapture %}
{% else %}
{% capture jekyll_toc %}{{ jekyll_toc }}</li>{% endcapture %}
{% endif %}

{% capture my_toc %}{{ my_toc }}
{{ space }}{{ listModifier }} {{ listItemClass }} {{ list_item }}{% if include.anchor_class %}{:.{{ include.anchor_class }}}{% endif %}{% endcapture %}
{% capture jekyll_toc %}{{ jekyll_toc }}<li{{ listItemClass }}>{{ listItem }}{% endcapture %}

{% assign previousLevel = indentAmount %}
{% assign lastLevel = currLevel %}
{% assign firstHeader = false %}
{% endfor %}

{% if include.class and include.class != blank %}
{% capture my_toc %}{:.{{ include.class }}}
{{ my_toc | lstrip }}{% endcapture %}
{% endif %}
{% assign repeatCount = minHeader | minus: 1 %}
{% assign repeatCount = lastLevel | minus: repeatCount %}
{% for i in (1..repeatCount) %}
{% capture jekyll_toc %}{{ jekyll_toc }}</li></{{ listModifier }}>{% endcapture %}
{% endfor %}

{% if include.id %}
{% capture my_toc %}{: #{{ include.id }}}
{{ my_toc | lstrip }}{% endcapture %}
{% endif %}
{% if jekyll_toc != '' %}
{% assign rootAttributes = '' %}
{% if include.class and include.class != blank %}
{% capture rootAttributes %} class="{{ include.class | split: '.' | join: ' ' }}"{% endcapture %}
{% endif %}

<!--
If we have a submenu class, we need to close off all the remaining list item groups so that submenu classes are
applied correctly to them
-->
{% if include.submenu_class != blank %}
<!-- The last level of indentation that we were at, we need to work backwards from there closing each group -->
{% for i in (1..previousLevel) %}
{% assign lvl = previousLevel | plus: 1 | minus: i %} <!-- Invert the indent level based on `i` -->
{% assign closingSpace = '' %}

{% for i in (1..lvl) %}
{% assign closingSpace = closingSpace | prepend: ' ' %}
{% endfor %}
{% if include.id and include.id != blank %}
{% capture rootAttributes %}{{ rootAttributes }} id="{{ include.id }}"{% endcapture %}
{% endif %}

{% capture my_toc %}{{ my_toc }}
{{ closingSpace }}{:.{{ include.submenu_class | replace: '%level%', lvl }}}{% endcapture %}
{% endfor %}
{% if rootAttributes %}
{% assign nodes = jekyll_toc | split: '>' %}
{% capture jekyll_toc %}<{{ listModifier }}{{ rootAttributes }}>{{ nodes | shift | join: '>' }}>{% endcapture %}
{% endif %}
{% endif %}
{% endcapture %}{% assign tocWorkspace = '' %}{{ my_toc | markdownify | strip }}
{% endcapture %}{% assign tocWorkspace = '' %}{{ deprecation_warnings }}{{ jekyll_toc }}
15 changes: 15 additions & 0 deletions _tests/base_url-deprecated.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
---

{% capture markdown %}
# Heading 1
{% endcapture %}
{% assign text = markdown | markdownify %}

{% include toc.html html=text baseurl="example.org" %}

<!-- /// -->

<ul>
<li><a href="example.org#heading-1">Heading 1</a></li>
</ul>
2 changes: 1 addition & 1 deletion _tests/base_url.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
{% endcapture %}
{% assign text = markdown | markdownify %}

{% include toc.html html=text baseurl="example.org" %}
{% include toc.html html=text base_url="example.org" %}

<!-- /// -->

Expand Down
50 changes: 50 additions & 0 deletions _tests/skipHeadingsWithNoIDs-Deprecated.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
# https://github.com/allejo/jekyll-toc/issues/32
---

{% capture markdown %}
## Sample Usage

<div>
<h1 class="page-title">My Awesome Example Page</h1>
<h2 class="page-subtitle">With an awesome subtitle</h2>
<a href='/' id="dummy-link">Dummy Link</a>
</div>

### Known Problems

Lots!

### Resources

#### Paid

#### Free
{% endcapture %}
{% assign text = markdown | markdownify %}

{% include toc.html html=text skipNoIDs=true %}

<!-- /// -->

<ul>
<li>
<a href="#sample-usage">Sample Usage</a>
<ul>
<li>
<a href="#known-problems">Known Problems</a>
</li>
<li>
<a href="#resources">Resources</a>
<ul>
<li>
<a href="#paid">Paid</a>
</li>
<li>
<a href="#free">Free</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
2 changes: 1 addition & 1 deletion _tests/skipHeadingsWithNoIDs.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Lots!
{% endcapture %}
{% assign text = markdown | markdownify %}

{% include toc.html html=text skipNoIDs=true %}
{% include toc.html html=text skip_no_ids=true %}

<!-- /// -->

Expand Down
21 changes: 13 additions & 8 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,22 @@
import unittest
import xml.etree.ElementTree as ET

class TestSequense(unittest.TestCase):
class TestSequence(unittest.TestCase):
pass

def test_generator(a, b):
def test(self):
self.assertEqual(a, b)
return test

def normalize_xml(xml):
tree = ET.fromstring(xml)
return re.sub('\\n\s+', '', ET.tostring(tree))
def normalize_xml(xml, test_file):
try:
tree = ET.fromstring(xml)
except:
print(f">> Invalid XML in {test_file}")
raise

return re.sub(r'(\\n|\n)\s*', '', str(ET.tostring(tree)), 0, re.MULTILINE)

if __name__ == '__main__':
test_path = os.path.join(os.getcwd(), '_site', 'tests')
Expand All @@ -22,12 +27,12 @@ def normalize_xml(xml):
path = os.path.join(test_path, test_file)
with open(path, 'r') as file:
actual, expected = file.read().split('<!-- /// -->')
actual = normalize_xml(actual)
expected = normalize_xml(expected)
actual = normalize_xml(actual, test_file)
expected = normalize_xml(expected, test_file)

# Add the unit test to our TestSequense
# Add the unit test to our TestSequence
test_name = 'test_{}'.format(test_file)
test = test_generator(actual, expected)
setattr(TestSequense, test_name, test)
setattr(TestSequence, test_name, test)

unittest.main()

0 comments on commit 7cf23b7

Please sign in to comment.