How to use the pscript.py2js function in pscript

To help you get started, we’ve selected a few pscript examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github flexxui / flexx / flexx / app / _modules.py View on Github external
self._provided_names.add(name)
                    self._pscript_code[name] = js
                    # Recurse
                    self._collect_dependencies_from_bases(val)
                    self._collect_dependencies(js, _dep_stack)
                else:
                    # Import from another module
                    self._import(mod_name, val.__name__, name)

        elif isinstance(val, type) and issubclass(val, bsdf.Extension):
            # A bit hacky mechanism to define BSDF extensions that also work in JS.
            # todo: can we make this better? See also app/_component2.py (issue #429)
            js = 'var %s = {name: "%s"' % (name, val.name)
            for mname in ('match', 'encode', 'decode'):
                func = getattr(val, mname + '_js')
                funccode = py2js(func, indent=1, inline_stdlib=False, docstrings=False)
                js += ',\n    ' + mname + ':' + funccode.split('=', 1)[1].rstrip(' \n;')
                self._collect_dependencies(funccode, _dep_stack)
            js += '};\n'
            js += 'serializer.add_extension(%s);\n' % name
            js = JSString(js)
            js.meta = funccode.meta
            self._pscript_code[name] = js
            self._deps.setdefault('flexx.app._clientcore',
                                 ['flexx.app._clientcore']).append('serializer')

        elif isinstance(val, pscript_types) and hasattr(val, '__module__'):
            # Looks like something we can convert using PScript
            mod_name = get_mod_name(val)
            if mod_name == self.name:
                # Define here
                try:
github flexxui / flexx / flexx / app / _modules.py View on Github external
self._collect_dependencies(funccode, _dep_stack)
            js += '};\n'
            js += 'serializer.add_extension(%s);\n' % name
            js = JSString(js)
            js.meta = funccode.meta
            self._pscript_code[name] = js
            self._deps.setdefault('flexx.app._clientcore',
                                 ['flexx.app._clientcore']).append('serializer')

        elif isinstance(val, pscript_types) and hasattr(val, '__module__'):
            # Looks like something we can convert using PScript
            mod_name = get_mod_name(val)
            if mod_name == self.name:
                # Define here
                try:
                    js = py2js(val, inline_stdlib=False, docstrings=False)
                except Exception as err:
                    t = 'JS in "%s" uses %r but cannot transpile it with PScript:\n%s'
                    raise ValueError(t % (self.filename, name, str(err)))
                self._provided_names.add(name)
                self._pscript_code[name] = js
                # Recurse
                if isinstance(val, type):
                    self._collect_dependencies_from_bases(val)
                self._collect_dependencies(js, _dep_stack)
            elif mod_name.endswith('.event._property'):
                return self._add_dep_from_event_module(name.split('.')[-1], name)
            else:
                # Import from another module
                self._import(mod_name, val.__name__, name)

        elif isinstance(val, RawJS):
github flexxui / flexx / flexx / app / _modules.py View on Github external
self._provided_names = set()
        self._imported_names = set()
        # Stuff defined in this module (in JS)
        # We use dicts so that we can "overwrite" them in interactive mode
        self._component_classes = {}
        self._pscript_code = {}
        self._js_values = {}
        # Dependencies
        self._deps = {}  # mod_name -> [mod_as_name, *imports]
        # Caches
        self._js_cache = None
        self._css_cache = None

        if is_pscript_module(self._pymodule):
            # PScript module; transpile as a whole
            js = py2js(self._pymodule, inline_stdlib=False, docstrings=False)
            self._pscript_code['__all__'] = js
            self._provided_names.update([n for n in js.meta['vars_defined']
                                         if not n.startswith('_')])
        else:
            self._init_default_objects()
github holoviz / holoviews / holoviews / plotting / bokeh / util.py View on Github external
def py2js_tickformatter(formatter, msg=''):
    """
    Uses py2js to compile a python tick formatter to JS code
    """
    try:
        from pscript import py2js
    except ImportError:
        param.main.param.warning(
            msg+'Ensure pscript is installed ("conda install pscript" '
            'or "pip install pscript")')
        return
    try:
        jscode = py2js(formatter, 'formatter')
    except Exception as e:
        error = 'Pyscript raised an error: {0}'.format(e)
        error = error.replace('%', '%%')
        param.main.param.warning(msg+error)
        return

    args = _getargspec(formatter).args
    arg_define = 'var %s = tick;' % args[0] if args else ''
    return_js = 'return formatter();\n'
    jsfunc = '\n'.join([arg_define, jscode, return_js])
    match = re.search('(formatter \= function \(.*\))', jsfunc )
    return jsfunc[:match.start()] + 'formatter = function ()' + jsfunc[match.end():]
github manatlan / vbuild / vbuild / __init__.py View on Github external
"DESTROYED",
                ]:
                    lifecycles.append(
                        "%s: %s.prototype.%s," % (oname.lower(), classname, oname)
                    )
                else:
                    methods.append("%s: %s.prototype.%s," % (oname, classname, oname))
            elif oname == "__init__":
                props = list(obj.__code__.co_varnames)[1:]

    methods = "\n".join(methods)
    computeds = "\n".join(computeds)
    watchs = "\n".join(watchs)
    lifecycles = "\n".join(lifecycles)

    pyjs = pscript.py2js(
        code, inline_stdlib=genStdLibMethods
    )  # https://pscript.readthedocs.io/en/latest/api.html

    return (
        """
var %(name)s=(function() {

    %(pyjs)s

    function construct(constructor, args) {
        function F() {return constructor.apply(this, args);}
        F.prototype = constructor.prototype;
        return new F();
    }

    return Vue.component('%(name)s',{
github QuantStack / ipysheet / ipysheet / easy.py View on Github external
def renderer(code, name):
    """Adds a cell renderer (to the front end)

    Parameters
    ----------
    code : str or code or function objject
        If a string object, it is assumed to be a JavaScript snippet, else it is assumed
        to be a function or code object and will be transpiled to javascript using flexxui/pscript.
    name : name of the renderer
    """
    if not isinstance(code, six.string_types):
        from pscript import py2js
        code_transpiled = py2js(code, new_name='the_renderer', indent=4)
        code = '''
function() {
  %s
  return the_renderer

}()
''' % code_transpiled
    renderer = Renderer(code=code, name=name)
    return renderer