Created
June 16, 2016 09:55
-
-
Save nacyot/d0bc5d2f655ccb8a3dc2380a92df0ada to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import hashlib | |
| import datetime | |
| import json | |
| from IPython.core.magic import Magics, magics_class, cell_magic | |
| from IPython.display import HTML | |
| @magics_class | |
| class JavascriptMagics(Magics): | |
| TEMPLATE = """ | |
| <div id='cell-%(time_hash)s'></div> | |
| <script> | |
| require.config(%(paths)s); | |
| (function(){ | |
| var cell_id = '#cell-%(time_hash)s'; | |
| var cell = $(cell_id) | |
| require(%(libs)s, function(%(names)s){ | |
| %(cell)s | |
| }); | |
| })(); | |
| </script> | |
| """ | |
| SKETCH_TEMPLATE = """ | |
| <div id='cell-%(time_hash)s'></div> | |
| <script> | |
| require.config(%(paths)s); | |
| (function(){ | |
| var cell_id = '#cell-%(time_hash)s'; | |
| var cell = $(cell_id) | |
| require(%(libs)s, function(%(names)s){ | |
| var sketch = function(canvas) { | |
| with(canvas){ | |
| %(cell)s | |
| } | |
| } | |
| new p5(sketch, cell_id.substring(1, cell_id.length)); | |
| }); | |
| })(); | |
| </script> | |
| """ | |
| @cell_magic | |
| def javascript_d3js(self, line, cell): | |
| libs = ['d3', 'lodash'] | |
| params = { | |
| "time_hash": self.time_hash(), | |
| "cell": cell, | |
| "paths": self.paths(libs), | |
| "libs": str(libs), | |
| "names": ",".join(libs).replace('lodash', '_') | |
| } | |
| return HTML(self.TEMPLATE % params) | |
| @cell_magic | |
| def javascript_sketch(self, line, cell): | |
| libs = [lib.strip() for lib in line.split(',')] | |
| params = { | |
| "time_hash": self.time_hash(), | |
| "cell": cell, | |
| "paths": self.paths(libs), | |
| "libs": str(libs), | |
| "names": ",".join(libs).replace('lodash', '_') | |
| } | |
| return HTML(self.SKETCH_TEMPLATE % params) | |
| @cell_magic | |
| def javascript_local(self, line, cell): | |
| libs = [lib.strip() for lib in line.split(',')] | |
| params = { | |
| "time_hash": self.time_hash(), | |
| "cell": cell, | |
| "paths": self.paths(libs), | |
| "libs": str(libs), | |
| "names": ",".join(libs).replace('lodash', '_') | |
| } | |
| return HTML(self.TEMPLATE % params) | |
| def time_hash(self): | |
| return hashlib.md5(datetime.datetime.now().strftime("%a:%d:%b:%Y:%H:%M:%S.%f").encode('utf-8')).hexdigest() | |
| def paths(self, libs): | |
| return json.dumps({ | |
| 'paths': {name: "/custom/{}/{}".format(name, name) for name in libs} | |
| }) | |
| def load_ipython_extension(ipython): | |
| ipython.register_magics(JavascriptMagics) | |
| def unload_ipython_extension(ipython): | |
| pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment