Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exclude submenu and TOC items for excluded folders. #106

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/options.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ plugins:
include_css: true
enabled: true
exclude:
include:
print_docs_dir: ""
```

`add_to_navigation`
Expand Down Expand Up @@ -91,4 +93,8 @@ plugins:
```

`exclude`
: Default is empty. Allows to specify a list of page source paths that should not be included in the print page. See [Do Not Print](how-to/do_not_print.md#ignoring-an-entire-page) for more info.
: Default is empty. Allows to specify a list of page source paths that should not be included in the print page. See [Do Not Print](how-to/do_not_print.md#ignoring-an-entire-page) for more info.
`include`
: Default is * to include the entire site. Allows to specify a list of page source paths that is then filtered by the exclude options to create a final list that should be included in the print page.
`print_docs_dir`
: Default is "" to use the site docs_dir. This can be set to a sub folder of the site docs_dir to set the root for print_site.
21 changes: 17 additions & 4 deletions mkdocs_print_site_plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
from mkdocs.exceptions import PluginError

from mkdocs_print_site_plugin.renderer import Renderer
from mkdocs_print_site_plugin.utils import flatten_nav, get_theme_name
from mkdocs_print_site_plugin.utils import flatten_nav, get_theme_name, find_new_root
from mkdocs_print_site_plugin.urls import is_external

logger = logging.getLogger("mkdocs.plugins")

HERE = os.path.dirname(os.path.abspath(__file__))

from mkdocs_print_site_plugin.exclude import exclude

class PrintSitePlugin(BasePlugin):
"""
Expand All @@ -42,6 +42,8 @@ class PrintSitePlugin(BasePlugin):
("include_css", config_options.Type(bool, default=True)),
("enabled", config_options.Type(bool, default=True)),
("exclude", config_options.Type(list, default=[])),
("include", config_options.Type(list, default=["*"])),
("print_docs_dir", config_options.Type(str, default="")),
)

def on_config(self, config, **kwargs):
Expand Down Expand Up @@ -180,6 +182,8 @@ def on_config(self, config, **kwargs):
self.context = {}

return config



def on_nav(self, nav, config, files, **kwargs):
"""
Expand All @@ -192,8 +196,17 @@ def on_nav(self, nav, config, files, **kwargs):
return nav

# Save the (order of) pages and sections in the navigation before adding the print page
self.renderer.items = nav.items
self.all_pages_in_nav = flatten_nav(nav.items)
print_dir=self.config.get("print_docs_dir","")
x = find_new_root(nav.items,print_dir )
if hasattr(x, 'children'):
self.renderer.items = x.children
self.all_pages_in_nav = flatten_nav(x.children)
else:
self.renderer.items = x
self.all_pages_in_nav = flatten_nav(x)

# self.renderer.items = nav.items
# self.all_pages_in_nav = flatten_nav(nav.items)

# Optionally add the print page to the site navigation
if self.config.get("add_to_navigation"):
Expand Down
105 changes: 61 additions & 44 deletions mkdocs_print_site_plugin/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def write_combined(self):
html += self._toc()

def get_html_from_items(
items: list, dir_urls: bool, excluded_pages: list, section_depth: int = 0
items: list, dir_urls: bool, included_pages: list, excluded_pages: list, section_depth: int = 0
) -> str:
"""
Get all the HTML from the pages.
Expand All @@ -81,6 +81,12 @@ def get_html_from_items(

for item in items:
if item.is_page:
# Do not exclude page in print page if included
if "Policies" in item.file.src_path:
x = item.file.src_path
if not exclude(item.file.src_path,included_pages):
logging.debug(f"Excluding page '{item.file.src_path}'")
continue
# Do not include page in print page if excluded
if exclude(item.file.src_path, excluded_pages):
logging.debug(f"Excluding page '{item.file.src_path}'")
Expand Down Expand Up @@ -118,32 +124,35 @@ def get_html_from_items(
)

if item.is_section:
items_html += """
<h%s class='nav-section-title' id='section-%s'>
%s <a class='headerlink' href='#section-%s' title='Permanent link'>↵</a>
</h%s>
""" % (
min(6, section_depth + 1),
to_snake_case(item.title),
item.title,
to_snake_case(item.title),
min(6, section_depth + 1),
)
items_html += get_html_from_items(
item.children, dir_urls, excluded_pages, section_depth + 1
)
# We also need to indicate the end of section page
# We do that using a h1 with a specific class
# In CSS we display:none, in JS we can use it for formatting the table of contents.
items_html += (
"<h1 class='nav-section-title-end'>Ended: %s</h1>" % item.title
section_html=get_html_from_items(
item.children, dir_urls, included_pages, excluded_pages, section_depth + 1
)
if len(section_html)>0:
items_html += """
<h%s class='nav-section-title' id='section-%s'>
%s <a class='headerlink' href='#section-%s' title='Permanent link'>↵</a>
</h%s>
""" % (
min(6, section_depth + 1),
to_snake_case(item.title),
item.title,
to_snake_case(item.title),
min(6, section_depth + 1),
)
items_html += section_html
# We also need to indicate the end of section page
# We do that using a h1 with a specific class
# In CSS we display:none, in JS we can use it for formatting the table of contents.
items_html += (
"<h1 class='nav-section-title-end'>Ended: %s</h1>" % item.title
)
return items_html

html += get_html_from_items(
self._get_items(),
dir_urls=self.mkdocs_config.get("use_directory_urls"),
excluded_pages=self.plugin_config.get("exclude", []),
included_pages=self.plugin_config.get("include", []),
excluded_pages=self.plugin_config.get("exclude", [])
)

html += "</div>"
Expand Down Expand Up @@ -218,15 +227,29 @@ def get_toc_sidebar(self) -> TableOfContents:

Reference: https://github.com/mkdocs/mkdocs/blob/master/mkdocs/structure/toc.py
"""
toc = []

if self.plugin_config.get("enumerate_headings"):
chapter_number = 0
section_number = 0
toc = []
toc = self.get_toc_sidebar_section(items=self._get_items(),included_pages=self.plugin_config.get("include", []), excluded_pages=self.plugin_config.get("exclude", []))


for item in self._get_items():
return TableOfContents(toc)

def get_toc_sidebar_section(self, items: list, included_pages: list, excluded_pages: list, level: int = 0, chapter_number:int =0, section_number:int =0 ):
toc=[]
for item in items:
if item.is_page:
page_key = get_page_key(item.url)
# Do not exclude page in print page if included
if not exclude(item.file.src_path,included_pages):
logging.debug(f"Excluding page '{item.file.src_path}'")
continue
# Do not include page in print page if excluded
if exclude(item.file.src_path, excluded_pages):
logging.debug(f"Excluding page '{item.file.src_path}'")
continue
# navigate to top of page if page is homepage
if page_key == "index":
page_key = ""
Expand All @@ -239,7 +262,6 @@ def get_toc_sidebar(self) -> TableOfContents:
toc.append(AnchorLink(title=title, id=f"{page_key}", level=0))

if item.is_section:

if self.plugin_config.get("enumerate_headings"):
section_number += 1
title = f"{int_to_roman(section_number)}. {item.title}"
Expand All @@ -249,24 +271,19 @@ def get_toc_sidebar(self) -> TableOfContents:
section_link = AnchorLink(
title=title, id=f"section-{to_snake_case(item.title)}", level=0
)

subpages = [p for p in item.children if p.is_page]
for page in subpages:
if self.plugin_config.get("enumerate_headings"):
chapter_number += 1
title = f"{chapter_number}. {page.title}"
else:
title = page.title

page_key = get_page_key(page.url)
section_link.children.append(
AnchorLink(title=title, id=f"{page_key}", level=1)
)

toc.append(section_link)

return TableOfContents(toc)

section_toc = self.get_toc_sidebar_section(items=item.children,
included_pages=included_pages,
excluded_pages=excluded_pages,
level=(level+1),
chapter_number = chapter_number,
section_number=section_number )
if len(section_toc) > 0:
toc.append(section_link)
for link in section_toc:
toc.append(link)
else:
section_number -= 1
return toc


def int_to_roman(num):
Expand Down Expand Up @@ -294,4 +311,4 @@ def int_to_roman(num):
for (n, roman) in lookup:
(d, num) = divmod(num, n)
res += roman * d
return res
return res
29 changes: 28 additions & 1 deletion mkdocs_print_site_plugin/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,34 @@ def get_theme_name(config) -> str:
else:
return name


def find_new_root( root, path):
# Split the path by '/'
path_parts = path.strip('/').split('/')

# Recursive helper function
def _find_node(current_node, parts):
if not parts:
return current_node

# Get the next part of the path
next_part = parts[0]

# Look for the next node among the current node's children
if not hasattr(current_node, 'children'):
return None
for child in current_node.children:
if child.is_section:
if child.title in next_part:
return _find_node(child, parts[1:])

return None # If the node is not found
for node in root:
if node.is_section:
if node.title == path_parts[0]:
return _find_node(node, path_parts[1:])

return None

def flatten_nav(items):
"""
Create a flat list of pages from a nested navigation.
Expand Down