]> git.ipfire.org Git - ipfire.org.git/commitdiff
wiki: Add preview for editing pages
authorMichael Tremer <michael.tremer@ipfire.org>
Thu, 30 May 2019 13:15:15 +0000 (14:15 +0100)
committerMichael Tremer <michael.tremer@ipfire.org>
Thu, 30 May 2019 13:15:15 +0000 (14:15 +0100)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/backend/wiki.py
src/scss/style.scss
src/templates/wiki/edit.html
src/web/__init__.py
src/web/wiki.py

index 51aa2b26a26cb42080a840dee0239620371a1e8f..e3275c2a3472b8a1e5b724bd9451d066f33a2cc4 100644 (file)
@@ -213,20 +213,13 @@ class Wiki(misc.Object):
                        if file and file.is_image():
                                return file
 
+       def render(self, path, text):
+               r = WikiRenderer(self.backend, path)
 
-class Page(misc.Object):
-       # Wiki links
-       wiki_link = re.compile(r"\[\[([\w\d\/\-\.]+)(?:\|(.+?))?\]\]")
-
-       # External links
-       external_link = re.compile(r"\[\[((?:ftp|git|https?|rsync|sftp|ssh|webcal)\:\/\/.+?)(?:\|(.+?))?\]\]")
-
-       # Interwiki links e.g. [[wp>IPFire]]
-       interwiki_link = re.compile(r"\[\[(\w+)>(.+?)(?:\|(.+?))?\]\]")
+               return r.render(text)
 
-       # Mail link
-       email_link = re.compile(r"\[\[([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)(?:\|(.+?))?\]\]")
 
+class Page(misc.Object):
        def init(self, id, data=None):
                self.id = id
                self.data = data
@@ -296,127 +289,13 @@ class Page(misc.Object):
                if self.data.author_uid:
                        return self.backend.accounts.get_by_uid(self.data.author_uid)
 
-       def _render_wiki_link(self, m):
-               path, alias = m.groups()
-
-               # Allow relative links
-               if not path.startswith("/"):
-                       path = os.path.join(self.page, path)
-
-               # Normalise links
-               path = os.path.normpath(path)
-
-               return """<a href="%s">%s</a>""" % (
-                       path,
-                       alias or self.backend.wiki.get_page_title(path),
-               )
-
-       def _render_external_link(self, m):
-               url, alias = m.groups()
-
-               return """<a class="link-external" href="%s">%s</a>""" % (url, alias or url)
-
-       def _render_interwiki_link(self, m):
-               wiki = m.group(1)
-               if not wiki:
-                       return
-
-               # Retrieve URL
-               try:
-                       url, repl, icon = INTERWIKIS[wiki]
-               except KeyError:
-                       logging.warning("Invalid interwiki: %s" % wiki)
-                       return
-
-               # Name of the page
-               name = m.group(2)
-
-               # Expand URL
-               url = url % {
-                       "name" : name,
-                       "url"  : urllib.parse.quote(name),
-               }
-
-               # Get alias (if present)
-               alias = m.group(3)
-
-               if not alias and repl:
-                       alias = repl % name
-
-               # Put everything together
-               s = []
-
-               if icon:
-                       s.append("<span class=\"%s\"></span>" % icon)
-
-               s.append("""<a class="link-external" href="%s">%s</a>""" % (url, alias or name))
-
-               return " ".join(s)
-
-       def _render_email_link(self, m):
-               address, alias = m.groups()
-
-               return """<a class="link-external" href="mailto:%s">%s</a>""" \
-                       % (address, alias or address)
-
-       def _render(self, text):
-               logging.debug("Rendering %s" % self)
-
-               # Link images
-               replacements = []
-               for match in re.finditer(r"!\[(.*?)\]\((.*?)\)", text):
-                       alt_text, url = match.groups()
-
-                       # Skip any absolute and external URLs
-                       if url.startswith("/") or url.startswith("https://") or url.startswith("http://"):
-                               continue
-
-                       # Try to split query string
-                       url, delimiter, qs = url.partition("?")
-
-                       # Parse query arguments
-                       args = urllib.parse.parse_qs(qs)
-
-                       # Find image
-                       file = self.backend.wiki.find_image(self.page, url)
-                       if not file:
-                               continue
-
-                       # Scale down the image if not already done
-                       if not "s" in args:
-                               args["s"] = "768"
-
-                       # Format URL
-                       url = "%s?%s" % (file.url, urllib.parse.urlencode(args))
-
-                       replacements.append((match.span(), file, alt_text, url))
-
-               # Apply all replacements
-               for (start, end), file, alt_text, url in reversed(replacements):
-                       text = text[:start] + "[![%s](%s)](%s?action=detail)" % (alt_text, url, file.url) + text[end:]
-
-               # Handle wiki links
-               text = self.wiki_link.sub(self._render_wiki_link, text)
-
-               # Handle interwiki links
-               text = self.interwiki_link.sub(self._render_interwiki_link, text)
-
-               # Handle external links
-               text = self.external_link.sub(self._render_external_link, text)
-
-               # Handle email links
-               text = self.email_link.sub(self._render_email_link, text)
-
-               # Borrow this from the blog
-               return self.backend.blog._render_text(text, lang="markdown")
-
        @property
        def markdown(self):
                return self.data.markdown or ""
 
        @property
        def html(self):
-               return self._render(self.markdown)
+               return self.backend.wiki.render(self.page, self.markdown)
 
        @property
        def timestamp(self):
@@ -600,3 +479,134 @@ class File(misc.Object):
                self.memcache.set(cache_key, thumbnail)
 
                return thumbnail
+
+
+class WikiRenderer(misc.Object):
+       # Wiki links
+       wiki_link = re.compile(r"\[\[([\w\d\/\-\.]+)(?:\|(.+?))?\]\]")
+
+       # External links
+       external_link = re.compile(r"\[\[((?:ftp|git|https?|rsync|sftp|ssh|webcal)\:\/\/.+?)(?:\|(.+?))?\]\]")
+
+       # Interwiki links e.g. [[wp>IPFire]]
+       interwiki_link = re.compile(r"\[\[(\w+)>(.+?)(?:\|(.+?))?\]\]")
+
+       # Mail link
+       email_link = re.compile(r"\[\[([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)(?:\|(.+?))?\]\]")
+
+       def init(self, path):
+               self.path = path
+
+       def _render_wiki_link(self, m):
+               path, alias = m.groups()
+
+               # Allow relative links
+               if not path.startswith("/"):
+                       path = os.path.join(self.path, path)
+
+               # Normalise links
+               path = os.path.normpath(path)
+
+               return """<a href="%s">%s</a>""" % (
+                       path,
+                       alias or self.backend.wiki.get_page_title(path),
+               )
+
+       def _render_external_link(self, m):
+               url, alias = m.groups()
+
+               return """<a class="link-external" href="%s">%s</a>""" % (url, alias or url)
+
+       def _render_interwiki_link(self, m):
+               wiki = m.group(1)
+               if not wiki:
+                       return
+
+               # Retrieve URL
+               try:
+                       url, repl, icon = INTERWIKIS[wiki]
+               except KeyError:
+                       logging.warning("Invalid interwiki: %s" % wiki)
+                       return
+
+               # Name of the page
+               name = m.group(2)
+
+               # Expand URL
+               url = url % {
+                       "name" : name,
+                       "url"  : urllib.parse.quote(name),
+               }
+
+               # Get alias (if present)
+               alias = m.group(3)
+
+               if not alias and repl:
+                       alias = repl % name
+
+               # Put everything together
+               s = []
+
+               if icon:
+                       s.append("<span class=\"%s\"></span>" % icon)
+
+               s.append("""<a class="link-external" href="%s">%s</a>""" % (url, alias or name))
+
+               return " ".join(s)
+
+       def _render_email_link(self, m):
+               address, alias = m.groups()
+
+               return """<a class="link-external" href="mailto:%s">%s</a>""" \
+                       % (address, alias or address)
+
+       def render(self, text):
+               logging.debug("Rendering %s" % self.path)
+
+               # Link images
+               replacements = []
+               for match in re.finditer(r"!\[(.*?)\]\((.*?)\)", text):
+                       alt_text, url = match.groups()
+
+                       # Skip any absolute and external URLs
+                       if url.startswith("/") or url.startswith("https://") or url.startswith("http://"):
+                               continue
+
+                       # Try to split query string
+                       url, delimiter, qs = url.partition("?")
+
+                       # Parse query arguments
+                       args = urllib.parse.parse_qs(qs)
+
+                       # Find image
+                       file = self.backend.wiki.find_image(self.path, url)
+                       if not file:
+                               continue
+
+                       # Scale down the image if not already done
+                       if not "s" in args:
+                               args["s"] = "768"
+
+                       # Format URL
+                       url = "%s?%s" % (file.url, urllib.parse.urlencode(args))
+
+                       replacements.append((match.span(), file, alt_text, url))
+
+               # Apply all replacements
+               for (start, end), file, alt_text, url in reversed(replacements):
+                       text = text[:start] + "[![%s](%s)](%s?action=detail)" % (alt_text, url, file.url) + text[end:]
+
+               # Handle wiki links
+               text = self.wiki_link.sub(self._render_wiki_link, text)
+
+               # Handle interwiki links
+               text = self.interwiki_link.sub(self._render_interwiki_link, text)
+
+               # Handle external links
+               text = self.external_link.sub(self._render_external_link, text)
+
+               # Handle email links
+               text = self.email_link.sub(self._render_email_link, text)
+
+               # Borrow this from the blog
+               return self.backend.blog._render_text(text, lang="markdown")
index e183595b5e1aa9d11fbb06a55a534b48f54c6046..700971534dcd56d1e2dba83606923d1d6ca7c714 100644 (file)
@@ -30,6 +30,7 @@
 @import "../bootstrap/scss/list-group";
 @import "../bootstrap/scss/close";
 @import "../bootstrap/scss/modal";
+@import "../bootstrap/scss/spinners";
 @import "../bootstrap/scss/utilities";
 @import "../bootstrap/scss/print";
 
@@ -315,6 +316,29 @@ section {
        }
 }
 
+#preview {
+       // Hide the spinner by default
+       #spinner {
+               display: none;
+       }
+
+       #preview-content {
+               @include transition(opacity .5s linear);
+       }
+
+       &.updating {
+               // Show the spinner during updates
+               #spinner {
+                       display: block;
+               }
+
+               // While updating, we face out the content
+               #preview-content {
+                       opacity: 0.5;
+               }
+       }
+}
+
 hr.divider {
        border-color: rgba($dark, .15);
        margin-top: 2rem;
index c5bec0ea9f4bff07cacc0dafb0731ea0cadc6c2d..8933b4008b37996fb18460ce76aad4c370c0711c 100644 (file)
@@ -11,7 +11,7 @@
 {% end block %}
 
 {% block main %}
-       <div class="card">
+       <div class="card mb-4">
                <div class="card-body">
                        <h4 class="card-title">
                                {% if page %}{{ _("Edit %s") % page.title }}{% else %}{{ _("Create A New Page") }}{% end %}
@@ -21,7 +21,7 @@
                                {% raw xsrf_form_html() %}
 
                                <div class="form-group">
-                                       <textarea class="form-control" rows="16" name="content" placeholder="{{ _("Text") }}"
+                                       <textarea class="form-control" rows="16" name="content" id="content" placeholder="{{ _("Text") }}"
                                                >{% if page and page.markdown %}{{ page.markdown }}{% end %}</textarea>
                                </div>
 
                        </form>
                </div>
        </div>
+
+       <div id="preview" class="fade show">
+               <div class="d-flex align-items-center mb-4">
+                       <h4 class="mb-0">{{ _("Preview") }}</h4>
+                       <div id="spinner" class="spinner-border ml-auto" role="status" aria-hidden="true"></div>
+               </div>
+
+               <div class="card">
+                       <div class="card-body mb-0">
+                               <div id="preview-content" class="wiki-content mb-0">
+                                       {{ _("Loading...") }}
+                               </div>
+                       </div>
+               </div>
+       </div>
+{% end block %}
+
+{% block javascript %}
+       <script type="text/javascript">
+               var update = null;
+
+               $(document).ready(function() {
+                       var preview = $("#preview");
+                       preview.hide();
+
+                       $("#content").on("keyup", function(e) {
+                               if (update)
+                                       clearTimeout(update);
+
+                               var content = $(this).val();
+
+                               // If the field is all empty, we will hide it
+                               if (content)
+                                       preview.show();
+                               else
+                                       preview.hide();
+
+                               // Go into update mode
+                               preview.addClass("updating");
+
+                               update = setTimeout(function() {
+                                       var c = $("#preview-content");
+
+                                       $.post("{{ page.url }}/_render", { content : content },
+                                               function(data) {
+                                                       c.html(data);
+
+                                                       // Update finished
+                                                       preview.removeClass("updating");
+                                               }
+                                       );
+                               }, 750);
+                       });
+               });
+       </script>
 {% end block %}
index ea797952562c9ef9e18994e1a38d28e19a9d9dd2..af11c98f059916cd4d9499ab05518e16471af2d2 100644 (file)
@@ -290,6 +290,7 @@ class Application(tornado.web.Application):
 
                        # Actions
                        (r"([A-Za-z0-9\-_\/]+)?/_edit", wiki.ActionEditHandler),
+                       (r"([A-Za-z0-9\-_\/]+)?/_render", wiki.ActionRenderHandler),
                        (r"([A-Za-z0-9\-_\/]+)?/_(watch|unwatch)", wiki.ActionWatchHandler),
                        (r"/actions/upload", wiki.ActionUploadHandler),
 
index 5a37ea22d80c972d348fec551f4b4ac5c0e85e26..b4c01e39851ad6b84ea690933bb56c5dc6c29ff1 100644 (file)
@@ -105,6 +105,20 @@ class ActionWatchHandler(auth.CacheMixin, base.BaseHandler):
                self.redirect(page.url)
 
 
+class ActionRenderHandler(auth.CacheMixin, base.BaseHandler):
+       def check_xsrf_cookie(self):
+               pass # disabled
+
+       @tornado.web.authenticated
+       def post(self, path):
+               content = self.get_argument("content")
+
+               # Render the content
+               html = self.backend.wiki.render(path, content)
+
+               self.finish(html)
+
+
 class FilesHandler(auth.CacheMixin, base.BaseHandler):
        @tornado.web.authenticated
        def get(self, path):