Skip to content

Commit

Permalink
feat: Add optional navbar to html export (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
Krande authored Jan 12, 2024
1 parent fa01441 commit 605474c
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 7 deletions.
2 changes: 1 addition & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ include README.md
include src/paradoc/resources/default_style.css
include src/paradoc/resources/template.docx
include src/paradoc/resources/template_blank.docx
include src/paradoc/rules/resources/*.json
include src/paradoc/io/html/js/*.js
include src/paradoc/svg/templates/*.svg
include src/paradoc/svg/templates/titleblocks/*.svg
6 changes: 3 additions & 3 deletions src/paradoc/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def __init__(
self.md_files_main = []
self.md_files_app = []
self.metadata_file = None
self._use_default_html_style = use_default_html_style
self.use_default_html_style = use_default_html_style
self._setup(create_dirs, clean_build_dir)

def _iter_md_files(self) -> Iterable[pathlib.Path]:
Expand Down Expand Up @@ -185,7 +185,7 @@ def compile(self, output_name, auto_open=False, metadata_file=None, export_forma
if self.metadata_file.exists() is False:
with open(self.metadata_file, "w") as f:
f.write('linkReferences: true\nnameInLink: true\nfigPrefix: "Figure"\ntblPrefix: "Table"')
if self._use_default_html_style is True:
if self.use_default_html_style is True:
f.write("\nstylesheet: style.css")
css_style = self.source_dir / "style.css"
if css_style.exists() is False:
Expand Down Expand Up @@ -222,7 +222,7 @@ def compile(self, output_name, auto_open=False, metadata_file=None, export_forma

self._perform_variable_substitution(False)
html = HTMLExporter(self)
html.export(dest_file)
html.export(dest_file, include_navbar=kwargs.get("include_navbar", True))
else:
raise NotImplementedError(f'Export format "{export_format}" is not yet supported')

Expand Down
31 changes: 29 additions & 2 deletions src/paradoc/io/html/exporter.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import pathlib
import shutil

import pypandoc

from paradoc import OneDoc
from paradoc.utils import copy_figures_to_dist

THIS_DIR = pathlib.Path(__file__).parent


class HTMLExporter:
def __init__(self, one_doc: OneDoc):
self.one_doc = one_doc

def export(self, dest_file):
def export(self, dest_file, include_navbar=True):
one = self.one_doc

md_main_str = "\n\n".join([md.read_built_file() for md in one.md_files_main])
Expand All @@ -19,7 +22,7 @@ def export(self, dest_file):

app_str = """\n\n\\appendix\n\n"""

md_app_str = "\n".join([md.read_built_file() for md in one.md_files_app])
md_app_str = "\n\n".join([md.read_built_file() for md in one.md_files_app])
combined_str = md_main_str + app_str + md_app_str

html_str = pypandoc.convert_text(
Expand All @@ -35,23 +38,47 @@ def export(self, dest_file):
],
filters=["pandoc-crossref"],
)

js_script = ""
if include_navbar:
js_script = "<script>\n" + open(THIS_DIR / "js/navbar.js", "r").read() + "\n</script>"

app_head_text = ""
if len(one.md_files_app) > 0:
app_file1 = open(one.md_files_app[0].path, "r").read()
for line in app_file1.splitlines():
if line.startswith("# "):
app_head_text = line[2:]
break

styled_html = f"""<html>
<head>
<meta name="data-appendix-start" content="{app_head_text}">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js">
</script>
{js_script}
</head>
<body>
<div class="content">
{html_str}
</div>
</body>
</html>"""

# styled_html.format(__custom_js_navbar__=js_script)

with open(dest_file, "w", encoding="utf-8") as f:
f.write(styled_html)

style_css_file = one.source_dir / "style.css"
if style_css_file.exists():
shutil.copy(style_css_file, dest_file.parent / "style.css")
else:
if self.one_doc.use_default_html_style:
from paradoc.common import MY_DEFAULT_HTML_CSS

shutil.copy(MY_DEFAULT_HTML_CSS, dest_file.parent / "style.css")

print(f'Successfully exported HTML to "{dest_file}"')
54 changes: 54 additions & 0 deletions src/paradoc/io/html/js/navbar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
document.addEventListener("DOMContentLoaded", function() {
const navbar = document.createElement("div");
navbar.className = "navbar";

const appendixStartText = document.querySelector('meta[name="data-appendix-start"]').getAttribute("content").replace(/\s+/g, '');

let counters = [0, 0, 0, 0, 0, 0];
let currentAppendixLetter = 'A';
let inAppendix = false;
const indentSize = 20; // Indent size in pixels

const headers = document.querySelectorAll("h1, h2, h3, h4, h5, h6");

headers.forEach(function(header) {
const headerText = header.textContent.replace(/\s+/g, '');
const level = parseInt(header.tagName.substring(1)) - 1; // Define level here

if (headerText === appendixStartText) {
inAppendix = true;
counters = [0, 0, 0, 0, 0, 0];
}

let number;
if (inAppendix) {
if (level === 0) { // Increment letter for each h1 in appendix
if (counters[0] > 0) { // Increment letter after the first h1
currentAppendixLetter = String.fromCharCode(currentAppendixLetter.charCodeAt(0) + 1);
}
counters = [0, 0, 0, 0, 0, 0];
}
counters[level]++;
number = (level === 0 ? "Appendix " : "") + currentAppendixLetter + (level > 0 ? "." + counters.slice(1, level + 1).join(".") : "");
} else {
counters[level]++;
number = counters.slice(0, level + 1).join(".");
}
// reset lower levels
for (let i = level + 1; i < counters.length; i++) {
counters[i] = 0;
}

header.id = header.id || "heading" + number;
header.textContent = number + " " + header.textContent;

const link = document.createElement("a");
link.href = "#" + header.id;
link.textContent = header.textContent;
link.style.paddingLeft = `${indentSize * level}px`;

navbar.appendChild(link);
});

document.body.prepend(navbar);
});
27 changes: 26 additions & 1 deletion src/paradoc/resources/default_style.css
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ html {

body {
color: #444;
font-family: Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif;
font-family: Arial, serif;
font-size: 12px;
line-height: 1.7;
padding: 1em;
Expand Down Expand Up @@ -325,4 +325,29 @@ table td {
h2, h3 {
page-break-after: avoid;
}
}

/* Basic styling for the navigation bar */
.navbar {
position: fixed;
top: 0;
left: 0;
width: 20%;
height: 100%;
overflow: auto;
background-color: #f0f0f0;
padding: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.navbar a {
display: block;
padding: 5px;
margin: 5px 0;
text-decoration: none;
color: black;
}

.navbar a:hover {
background-color: #ddd;
}

0 comments on commit 605474c

Please sign in to comment.