From 32c1b21ccab9667d3355d7d9d2d102c972ba5310 Mon Sep 17 00:00:00 2001 From: RunasSudo Date: Sat, 20 Jun 2020 23:05:33 +1000 Subject: [PATCH] Add page preview endpoint --- wikinote/__init__.py | 42 +++++++++++++++++++++++++++++++++++++++++- wikinote/markup.py | 9 ++++++--- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/wikinote/__init__.py b/wikinote/__init__.py index db52f88..a331135 100644 --- a/wikinote/__init__.py +++ b/wikinote/__init__.py @@ -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/') +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/') def image_view(name): fname = flask.safe_join(os.getcwd(), './data/images', name[0].upper(), name) diff --git a/wikinote/markup.py b/wikinote/markup.py index fec71f3..7f77b8f 100644 --- a/wikinote/markup.py +++ b/wikinote/markup.py @@ -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')