Add page preview endpoint

This commit is contained in:
RunasSudo 2020-06-20 23:05:33 +10:00
parent 3302ee9948
commit 32c1b21cca
Signed by: RunasSudo
GPG Key ID: 7234E476BF21C61A
2 changed files with 47 additions and 4 deletions

View File

@ -115,7 +115,7 @@ def page_toc(path):
page_source = f.read()
md = WNMarkdown()
page_content = md.convert(page_source)
_ = md.convert(page_source)
return flask.render_template('page_toc.html', page={
'path': path,
@ -123,6 +123,46 @@ def page_toc(path):
'toc': md.toc_tokens
})
@app.route('/preview/<path:path>')
def page_preview(path):
fname = flask.safe_join('./data/pages', path) + '.md'
if not os.path.exists(fname):
return ''
with(open(fname, 'r')) as f:
page_source = f.read()
md = WNMarkdown()
page_root = md.parse(page_source)
# Delete all but first section
for section in list(page_root[1:]):
page_root.remove(section)
# Delete all but introductory text
for elem in list(page_root[0][1:]):
page_root[0].remove(elem)
# Delete footnotes
def walk_tree(elem):
last_child = None
for child in list(elem):
if child.get('class') == 'footnote-ref':
if child.tail:
# Combine tail text
if last_child is not None:
last_child.tail += child.tail
else:
elem.text += child.tail
elem.remove(child)
walk_tree(child)
last_child = child
walk_tree(page_root[0])
page_content = md.serialise(page_root)
return page_content
@app.route('/image/<name>')
def image_view(name):
fname = flask.safe_join(os.getcwd(), './data/images', name[0].upper(), name)

View File

@ -75,9 +75,7 @@ class WNMarkdown(markdown.Markdown):
return root
# Based on Markdown.convert
def convert(self, source):
root = self.parse(source)
def serialise(self, root):
output = self.serializer(root)
if self.stripTopLevelTags:
@ -94,6 +92,11 @@ class WNMarkdown(markdown.Markdown):
return output.strip()
# Put it together
def convert(self, source):
root = self.parse(source)
return self.serialise(root)
def detab(self, text):
newtext = []
lines = text.split('\n')