Coverage for lino/utils/jsgen.py : 70%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -*- coding: UTF-8 -*- # Copyright 2009-2015 Luc Saffre # License: BSD (see file COPYING for details)
.. autosummary::
Example:
>>> class TextField(Component): ... declare_type = DECLARE_VAR >>> class Panel(Component): ... declare_type = DECLARE_VAR >>> fld1 = TextField(fieldLabel="Field 1",name='fld1',xtype='textfield') >>> fld2 = TextField(fieldLabel="Field 2",name='fld2',xtype='textfield') >>> fld3 = TextField(fieldLabel="Field 3",name='fld3',xtype='textfield') >>> p1 = Panel(title="Panel",name='p1',xtype='panel',items=[fld2,fld3]) >>> main = Component(title="Main",name='main',xtype='form',items=[fld1,p1]) >>> d = dict(main=main,wc=[1,2,3])
>>> for ln in declare_vars(d): ... print ln var fld11 = { "fieldLabel": "Field 1", "xtype": "textfield" }; var fld22 = { "fieldLabel": "Field 2", "xtype": "textfield" }; var fld33 = { "fieldLabel": "Field 3", "xtype": "textfield" }; var p14 = { "items": [ fld22, fld33 ], "xtype": "panel", "title": "Panel" };
>>> print py2js(d) { "main": { "items": [ fld11, p14 ], "xtype": "form", "title": "Main" }, "wc": [ 1, 2, 3 ] }
Another example...
>>> def onReady(name): ... yield js_line("hello = function() {") ... yield js_line("console.log(%s)" % py2js("Hello, " + name + "!")) ... yield js_line("}") >>> print py2js(onReady("World")) hello = function() { console.log("Hello, World!") } <BLANKLINE>
And yet another example (`/blog/2012/0208`)...
>>> chunk = '<a href="javascript:alert({"record_id": 122 })">Test</a>' >>> print py2js(chunk) "<a href=\"javascript:alert({"record_id": 122 })\">Test</a>"
>>> data_record = dict( ... title="Upload \"Aufenthaltserlaubnis\"", ... data=dict(owner=chunk)) >>> print py2js(data_record) { "data": { "owner": "<a href=\"javascript:alert({"record_id": 122 })\">Test</a>" }, "title": "Upload \"Aufenthaltserlaubnis\"" } >>> response = dict( ... message="Upload \"Aufenthaltserlaubnis\" wurde erstellt.", ... success=True, ... data_record=data_record) >>> print py2js(response) #doctest: +NORMALIZE_WHITESPACE { "message": "Upload \"Aufenthaltserlaubnis\" wurde erstellt.", "success": true, "data_record": { "data": { "owner": "<a href=\"javascript:alert({"record_id": 122 })\">Test</a>" }, "title": "Upload \"Aufenthaltserlaubnis\"" } }
"""
return ", ".join(["%s: %s" % (k, py2js(v)) for k, v in list(d.items())])
"""Run the given callable `func` with the given user profile `profile` activated. Optional args and kwargs are forwarded to the callable, and the return value is returned.
""" global _for_user_profile
_for_user_profile = old
return _for_user_profile
# def set_user_profile(up): # global _for_user_profile # _for_user_profile = up
# set_for_user_profile = set_user_profile
if isinstance(s, str): return s return json.dumps(s) # ,cls=DjangoJSONEncoder)
"A string that py2js will represent as is, not between quotes."
#~ def __repr__(self): #~ return self.s
return []
return []
#~ def js_before_body(self): #~ for v in self.subvars(): #~ for ln in v.js_before_body(): #~ yield ln for v in self.subvars(): for ln in v.js_body(): yield ln
#~ def js_after_body(self): #~ for v in self.subvars(): #~ for ln in v.js_after_body(): #~ yield ln
return self.value_template % py2js(self.value)
global VARIABLE_COUNTER self.ext_name = "var%s%d" % (self.ext_suffix, VARIABLE_COUNTER) else: id2js(name), self.ext_suffix, VARIABLE_COUNTER) #~ assert self.declare_type != DECLARE_INLINE
#~ if name is None: #~ assert self.declare_type == DECLARE_INLINE # ~ #self.name = "unnamed %s" % self.__class__.__name__ #~ else: #~ self.name = name #~ self.ext_name = id2js(name) + self.ext_suffix #~ self.ext_name = id2js(name) + self.ext_suffix
#~ if self.ext_name is None: raise Exception("20120920"+str(self.name)) #~ assert self.ext_name is not None return self.ext_name
yield "// begin js_declare %s" % self yield "// declare subvars of %s" % self for v in self.subvars(): for ln in v.js_declare(): yield ln yield "// end declare subvars of %s" % self value = self.js_value() if self.declare_type == DECLARE_INLINE: pass elif self.declare_type == DECLARE_VAR: yield "var %s = %s;" % (self.ext_name, value) elif self.declare_type == DECLARE_THIS: yield "this.%s = %s;" % (self.ext_name, value) yield "// end js_declare %s" % self
#~ def js_column_lines(self): #~ return []
return "this." + self.ext_name
return self.value_template % py2js(self.value)
"""A Component is a Variable whose value is a dict of otpions. Deserves more documentation.
"""
# note that we remove the "**" from options ;-)
"""Walk over this component and its children.""" items = self.value['items'] if not isinstance(items, (list, tuple)): items = [items] for i in items: for e in i.walk(): if e.is_visible(): yield e
"""A visible component """ # help_text = None #flex = None
# install `allow_read` permission handler:
self, True, self.debug_permissions, self.required_roles), self)
if self.hidden: return False return self.get_view_permission(_for_user_profile)
return self.allow_read(profile)
preferred_width=None, # help_text=None, required_roles=NOT_PROVIDED, **kw): #~ Component.__init__(self,name,**kw) self.height = height raise Exception( "20150628 %s has required_roles %s" % ( self, required_roles)) # if help_text is not None: # self.help_text = help_text
"This shows how elements are specified" name = Component.__str__(self) if self.width is None: return name if self.height is None: return name + ":%d" % self.width return name + ":%dx%d" % (self.width, self.height)
return str(self)
return (" " * level) + str(self)
if self.is_visible(): yield self
sep = u"</td><td>" cols = """ext_name name parent label __class__.__name__ elements js_value label_align vertical width preferred_width height preferred_height vflex""".split() yield '<tr><td>' + sep.join(cols) + '</td></tr>' for e in self.walk(): yield '<tr><td>' + sep.join([py2html(e, n) for n in cols]) + '</td></tr>'
""" Yields the Javascript lines that declare the given :class:`Variable` `v`. If `v` is a :class:`Component`, `list`, `tuple` or `dict` which contains other variables, recursively yields also the lines to declare these. """ _for_user_profile): return # DON'T return #~ 20120616 if not v.is_visible(): return #~ ok = True for ln in declare_vars(v.value): yield ln # DON'T return
#~ 20120616 if not v.is_visible(): return yield "this.%s = %s;" % (v.ext_name, v.js_value())
"""Note that None values are rendered as ``null`` (not ``undefined``.
""" #~ assert _for_user_profile is not None #~ logger.debug("py2js(%r)",v)
#~ if isinstance(v,LanguageInfo): #~ return v.django_code
#~ v = v.as_ext() #~ if not isinstance(v, basestring): #~ raise Exception("20120121b %r is of type %s" % (v,type(v))) #~ return v #~ v = force_text(v)
#~ if isinstance(v,etree.Element):
#~ if type(v) is types.GeneratorType: #~ raise Exception("Please don't call the generator function yourself") #~ return "\n".join([ln for ln in v]) #~ print 20120114, repr(v) #~ raise Exception("Please call the function yourself") return "\n".join([ln for ln in v()]) #~ return 'undefined' if (not isinstance(x, VisibleComponent)) or x.get_view_permission(_for_user_profile)]
"%s: %s" % (py2js(k), py2js(v)) for k, v in list(v.items()) if (not isinstance(v, VisibleComponent)) or v.get_view_permission(_for_user_profile) ])
return '"%s"' % v return '"%s"' % v.strftime(settings.SITE.date_format_strftime) return '"%s"' % v.strftime(settings.SITE.datetime_format_strftime) return '"%s"' % v.strftime(settings.SITE.time_format_strftime) if v.year < 1900: v = IncompleteDate(v) return '"%s"' % v.strftime(settings.SITE.date_format_strftime) return '"%s"' % v.strftime(settings.SITE.date_format_strftime)
return repr(v) # return json.encoder.encode_basestring(v) # print repr(v) # http://docs.djangoproject.com/en/dev/topics/serialization/ #~ if not isinstance(v, (str,unicode)): #~ raise Exception("20120121 %r is of type %s" % (v,type(v))) # try: # return json.dumps(v) # except TypeError as e: # raise TypeError("%r : %s" % (v, e)) # ~ return json.dumps(v,cls=DjangoJSONEncoder) # http://code.djangoproject.com/ticket/3324
import doctest doctest.testmod()
_test() |