Transition to mkwsref xblock (reference widget)
[mkwsxb-moved-to-github.git] / mkwsref / mkwsref / mkwsref.py
diff --git a/mkwsref/mkwsref/mkwsref.py b/mkwsref/mkwsref/mkwsref.py
new file mode 100644 (file)
index 0000000..dd0fce0
--- /dev/null
@@ -0,0 +1,71 @@
+"""Embed reference widget from MKWS, the MasterKey Widget Set"""
+
+import pkg_resources
+import random
+
+from xblock.core import XBlock
+from xblock.fields import Integer, Scope, String, Any, Boolean, Dict
+from xblock.fragment import Fragment
+
+class MKWSRef(XBlock):
+    """Embed reference widget from MKWS, the MasterKey Widget Set"""
+
+    # Fields
+    query = String(
+      help="Search query",
+      default="water",
+      scope=Scope.content
+    )
+    display_name = String(
+      default="MKWS Reference Widget",
+      scope=Scope.settings
+    )
+
+    def resource_string(self, path):
+        """Helper for accessing resources."""
+        data = pkg_resources.resource_string(__name__, path)
+        return data.decode("utf8")
+
+    def student_view(self, context=None):
+        """The primary view of the MKWS XBlock, shown to students when viewing courses."""
+        html = self.resource_string("static/html/student.html")
+        frag = Fragment(html.format(query=self.query, team=random.randint(0, 100000)))
+        # student.js uses require.js as it cannot guarantee mkws-complete.js has loaded 
+        # in studio without it. We'll need to add it if we're in the LMS:
+        frag.add_javascript_url("/static/js/vendor/require.js");
+        frag.add_javascript(self.resource_string("static/js/src/student.js"))
+        frag.initialize_js('MKWSRef')
+        return frag;
+
+    def author_view(self, context=None):
+        """View of the MKWS XBlock shown when authoring courses."""
+        html = self.resource_string("static/html/student.html")
+        frag = Fragment(html.format(query=self.query, team=random.randint(0, 100000)))
+        frag.add_javascript(self.resource_string("static/js/src/student.js"))
+        frag.initialize_js('MKWSRef')
+        return frag;
+
+    def studio_view(self, context=None):
+        """Studio configuration view."""
+        html = self.resource_string("static/html/settings.html")
+        frag = Fragment(html.format(query=self.query))
+        frag.add_javascript(self.resource_string("static/js/src/settings.js"))
+        frag.initialize_js('MKWSRefSettings')
+        return frag
+
+    @XBlock.json_handler
+    def update_settings(self, data, suffix=''):
+        """Studio configuration callback."""
+        self.query = data['query']
+        return {"result": "success"}
+
+    @staticmethod
+    def workbench_scenarios():
+        """A canned scenario for display in the workbench."""
+        return [
+            ("MKWSRef",
+             """<vertical_demo>
+                <mkwsref/>
+                </vertical_demo>
+             """),
+        ]