diff libervia/pages/blog/edit/_browser/__init__.py @ 1416:0554103ec700

pages (blog): new `edit` page: this page is used for new blog post and may be used for editing existing posts too. New `editor` module is using for autosave and tags editor. New `mbPreview` bridge method is used to generate preview when javascript is available.
author Goffi <goffi@goffi.org>
date Thu, 29 Apr 2021 16:55:07 +0200
parents
children 925a7c498cda
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libervia/pages/blog/edit/_browser/__init__.py	Thu Apr 29 16:55:07 2021 +0200
@@ -0,0 +1,58 @@
+from browser import document, window, aio, bind
+from aio_bridge import Bridge, BridgeException
+import editor
+import dialog
+from javascript import JSON
+from template import Template
+
+bridge = Bridge()
+item_tpl = Template('blog/item.html')
+tab_select = window.tab_select
+
+async def on_preview(evt):
+    elt = evt.target
+    tab_preview = document["tab_preview"]
+    tab_preview.clear()
+    form = document["blog_post_edit"]
+    data = {
+        "content_rich": form.select_one('textarea[name="body"]').value.strip()
+    }
+    title = form.select_one('input[name="title"]').value.strip()
+    if title:
+        data["title_rich"] = title
+    tags = form.select_one('input[name="tags"]').value.strip()
+    if tags:
+        data['tags'] = [t.strip() for t in tags.split(',') if t.strip()]
+    try:
+        preview_data = JSON.parse(await bridge.mbPreview("", "", JSON.stringify(data)))
+    except BridgeException as e:
+        dialog.notification.show(
+            f"Can't generate item preview: {e.message}",
+            level="error"
+        )
+    else:
+        tab_select(elt, "tab_preview", "is-active")
+        item_elt = item_tpl.get_elt({
+            "item": preview_data,
+            "dates_format": "short",
+        })
+        tab_preview <= item_elt
+
+
+@bind(".click_to_edit", "click")
+def on_edit(evt):
+    tab_select(evt.target, "tab_edit", "is-active")
+
+
+@bind(document["blog_post_edit"], "submit")
+def on_submit(evt):
+    submit_btn = document.select_one("button[type='submit']")
+    submit_btn.classList.add("is-loading")
+
+
+for elt in document.select('.click_to_preview'):
+    elt.bind("click", lambda evt: aio.run(on_preview(evt)))
+
+
+editor.set_form_autosave("blog_post_edit")
+editor.TagsEditor("input[name='tags']")