def index(self): d = RootController.plots.index() plot_data, plot_options = d['data'],d['options'] plot_options['series'] = [{'showMarker' : False} for series in plot_data] plot_options['title'] = 'Sine of the times' plot_options['axes']['xaxis']['renderer'] = \ js_function('$.jqplot.DateAxisRenderer') plot_options['axes']['xaxis']['tickOptions'] = {'formatString': '%T'} tmpl_context.plot_widget = plot_widget d = RootController.plots.pie() pie_data, pie_options = d['data'],d['options'] pie_options['title'] = 'Most recent value of each series' pie_options['seriesDefaults'] = { 'renderer' : js_function('$.jqplot.PieRenderer'), 'rendererOptions' : { 'sliceMargin' : 8, 'fill' : False, 'lineWidth' : 5 } } tmpl_context.pie_widget = pie_widget return dict(plot_data=plot_data, plot_options=plot_options, pie_data=pie_data, pie_options=pie_options)
def test_js_function_composition(self): f = js_function("f") g = js_function("g") h = js_function("h") y = js_symbol("y") obj = f(g(h("x", y))) eq_(str(obj), """f(g(h("x", y)))""")
def prepare(self): if not self.value: # XXX -- Doing this instead of twc.Deferred consciously. # twc.Deferred is/was nice, but the execution in post_define(...) of # cls._deferred = [k for k, v in cls.__dict__.iteritems() # if isinstance(v, pm.Deferred)] # with dir(..) instead of vars(..) is too costly. This is the only # place I'm aware of that actually uses deferred params. - threebean self.value = dt.datetime.now() super(CalendarDatePicker, self).prepare() self.safe_modify('resources') self.resources.extend([ twc.JSLink(parent=self.__class__, modname='tw2.dynforms', filename='static/calendar/lang/calendar-%s.js' % self.language), ]) self.add_call( twc.js_function('Calendar.setup')(dict( inputField=self.compound_id, ifFormat=self.validator.format, button=self.compound_id + ':trigger', showsTime=self.show_time)))
def prepare(self): super(TopicsBarChart, self).prepare() self.add_call(twc.js_function('tw2.d3.bar.schedule_halflife')( self.attrs['id'], 60000, # Halflife of one minute. 1000, 0.001, ))
def prepare(self): super(TopicsBarChart, self).prepare() self.add_call( twc.js_function('tw2.d3.bar.schedule_halflife')( self.attrs['id'], 60000, # Halflife of one minute. 1000, 0.001, ))
def prepare(self): super(Lightbox, self).prepare() copy_img_alt_src = """jQuery('a[data-lightbox]:not([data-title])>img[alt]:only-child').each( function(i, elem) { elem.parentElement.setAttribute( 'data-title', elem.getAttribute('alt')); });""" self.add_call(copy_img_alt_src) if self.options: self.add_call(js_function("lightbox.option")(self.options))
def prepare(self): super(DemoBarChart, self).prepare() # Register a javascript call to a utility function that tw2.d3 provides. # This one indicates that every element in the data should decay by a # certain halflife (2000ms), that function should be run every 1000ms, # and elements should just be removed if their value goes below a # certain epsilon (0.001) self.add_call(twc.js_function('tw2.d3.bar.schedule_halflife')( self.attrs['id'], 2000, 1000, 0.001, )) # This registers another javascript callback that is just nice for # testing. It schedules a callback that runs every 100 milliseconds # which adds random noise to the data elements. self.add_call(twc.js_function('tw2.d3.util.schedule_bump_random')( self.attrs['id'], 100 ))
def test_encoding_widget_id(self): from tw2.core import Widget w = Widget("foo") f = js_callback(js_function('jQuery')(w).click(js_symbol('onClick'))) args = {'onLoad': f} json = self.encode(args) eq_(json, '{"onLoad": function(){jQuery("foo").click(onClick)}}') json = self.encode({'args':args}) eq_(json, '{"args": {"onLoad": function(){jQuery("foo").click(onClick)}}}')
def prepare(self): self.resources.extend([ portletsbase.jquery_portlets_css, portletsbase.jquery_portlets_js, ]) super(Portlet, self).prepare() # tw2.jqplugins.ui already escapes the selector for us but # twc.js_function escapes it for us EVEN more. We gotta tone it down. less_escaped_selector = self.selector.replace('\\\\', '\\') setupCall = twc.js_function('makeIntoPortlet')(less_escaped_selector) self.add_call(setupCall)
def test_encoding_widget_id(self): from tw2.core import Widget w = Widget("foo") f = js_callback(js_function('jQuery')(w).click(js_symbol('onClick'))) args = {'onLoad': f} json = self.encode(args) eq_(json, '{"onLoad": function(){jQuery("foo").click(onClick)}}') json = self.encode({'args': args}) eq_(json, '{"args": {"onLoad": function(){jQuery("foo").click(onClick)}}}')
def prepare(self): self.resources.extend([ portletsbase.jquery_portlets_css, portletsbase.jquery_portlets_js, ]) if self.cookies: self.resources.append(cookiesbase.jquery_cookies_js) super(ColumnLayout, self).prepare() if self.cookies: restore = twc.js_function('restoreOrder')() self.add_call(restore)
def prepare(self): super(CalendarDatePicker, self).prepare() if not self.value and self.required: if callable(self.default): self.value = self.default() else: self.value = self.default try: self.strdate = self.value.strftime(self.date_format) except AttributeError: self.strdate = self.value calendar_options = {"inputField": self.compound_id, "showsTime": str(self.picker_shows_time).lower(), "ifFormat": self.date_format, "button": "%s_trigger" % self.compound_id} calendar_options.update(self.setup_options) self.add_call(twc.js_function('Calendar.setup')(calendar_options))
def prepare(self): # Check the types of everything int(self.width) int(self.height) int(self.interval) self.padding = [int(ele) for ele in self.padding] if self.data == None: raise ValueError("TimeSeriesChart must be provided a `data` dict") if type(self.data) != list: raise ValueError("TimeSeriesChart data must be of type `list`") super(TimeSeriesChart, self).prepare() self.add_call( twc.js_function("tw2.d3.timeseries.init")( self.attrs["id"], self.data, self.width, self.height, self.padding, self.interval, self.n, self.duration ) )
def prepare(self): # Check the types of everything int(self.width) int(self.height) int(self.interval) self.padding = [int(ele) for ele in self.padding] if self.data == None: raise ValueError("BarChart must be provided a `data` dict") super(BarChart, self).prepare() # Munge our data so d3 can understand it json = [{"key": k, "value": v} for k, v in self.data.iteritems()] self.add_call( twc.js_function("tw2.d3.bar.init")( self.attrs["id"], json, self.width, self.height, self.padding, self.interval ) )
def testJSFuncCallChained(self): rl = testapi.request(1, mw) options = {'foo': 20} jQuery = twc.js_function('jQuery') when_ready = lambda func: twc.js_callback( '$(document).ready(function(){' + str(func) + '});' ) class Dummy(twc.Widget): id = 'dummy' template = "tw2.core.test_templates.display_only_test_widget" def prepare(self): super(Dummy, self).prepare() self.add_call(when_ready( jQuery('.%s' % self.id).buildMenu(options) )) output = Dummy.display() eq_(len(rl['resources']), 1) eq_(str(rl['resources'][0]), '$(document).ready(function(){jQuery(".dummy").buildMenu({"foo": 20})});')
def testJSFuncCallChained(self): rl = testapi.request(1, mw) options = {'foo': 20} jQuery = twc.js_function('jQuery') when_ready = lambda func: twc.js_callback( '$(document).ready(function(){' + str(func) + '});') class Dummy(twc.Widget): id = 'dummy' template = "tw2.core.test_templates.display_only_test_widget" def prepare(self): super(Dummy, self).prepare() self.add_call( when_ready(jQuery('.%s' % self.id).buildMenu(options))) output = Dummy.display() eq_(len(rl['resources']), 1) eq_( str(rl['resources'][0]), '$(document).ready(function(){jQuery(".dummy").buildMenu({"foo": 20})});' )
def prepare(self): if not self.value: # XXX -- Doing this instead of twc.Deferred consciously. # twc.Deferred is/was nice, but the execution in post_define(...) of # cls._deferred = [k for k, v in cls.__dict__.iteritems() # if isinstance(v, pm.Deferred)] # with dir(..) instead of vars(..) is too costly. This is the only # place I'm aware of that actually uses deferred params. - threebean self.value = dt.datetime.now() super(CalendarDatePicker, self).prepare() self.safe_modify('resources') self.resources.extend([ twc.JSLink(parent=self.__class__, modname='tw2.dynforms', filename='static/calendar/lang/calendar-%s.js' % self.language), ]) self.add_call(twc.js_function('Calendar.setup')(dict( inputField = self.compound_id, ifFormat = self.validator.format, button = self.compound_id + ':trigger', showsTime = self.show_time )))
def prepare(self): super(CookieConsentWidget, self).prepare() if self.options: cfg = self.options else: cfg = self.default_options # always use full URLs for themes theme = cfg.get('theme', 'light-floating') rl = request_local() cfg['theme'] = ( rl['middleware'].config.res_prefix + 'tw2.cookieconsent/static/' + theme + ".css") # evaluate any lazy strings for key, value in cfg.items(): if is_lazy_string(value): cfg[key] = str(value) self.add_call(js_function( "(function(window,cfg){window.cookieconsent_options=cfg;})" )(js_symbol("window"), cfg), location='head') inject_resources()
def test_js_function(self): json = self.encode({"onLoad": js_function("do_something")("param")}) eq_(json, '{"onLoad": do_something("param")}')
def test_js_callback(self): eq_(str(js_callback("update_div")), 'update_div') eq_(str(js_callback(js_function('foo')(1,2,3))), 'function(){foo(1, 2, 3)}')
def prepare(self): self.add_call(js_function('CKEDITOR.replace')(self.id)) return super(CKEditor, self).prepare()
def prepare(self): super(HidingComponentMixin, self).prepare() self.safe_modify('resources') self.add_call(twc.js_function('twd_hiding_init')( self.compound_id, self.mapping))
import re import os import tw2.core as twc from pkg_resources import ResourceManager rm = ResourceManager() tinymce_dir = twc.DirLink(modname=__name__, filename="static/tiny_mce") #tinymce_js = twc.JSLink(modname=__name__, filename='static/tinymce.js') #tinymce_css = twc.CSSLink(modname=__name__, filename='static/tinymce.css') tinymce_js = twc.JSLink(modname=__name__, filename='static/tiny_mce/tiny_mce_src.js', init=twc.js_function('tinyMCE.init')) def _get_available_languages(): filename_re = re.compile(r'(\w+)\.js') langs = [] locale_dir = rm.resource_filename(__name__, "static/tiny_mce/langs") for filename in os.listdir(locale_dir): match = filename_re.match(filename) if match: langs.append(match.groups(0)[0]) return langs from formencode.validators import UnicodeString, Validator from genshi.core import Markup, stripentities
def test_jsonified_js_function(self): obj = {'f': js_function("$.awesome")} json = self.encode(obj) eq_(json, '{"f": $.awesome}')
import os import re import tw2.core as twc import tw2.forms as twf ace_js = twc.JSLink( modname=__name__, filename='static/ace/ace.js', edit=twc.js_function('ace.edit'), require=twc.js_function('ace.require'), ) ext_textarea_js = twc.JSLink( modname=__name__, filename='static/ace/ext-textarea.js', #Not safe for multiple widget instances per request #transformTextarea=ace_js.require('ace/ext/textarea').transformTextarea ) tw2_ace_js = twc.JSLink( modname=__name__, filename='static/tw2_ace.js', resources=[ace_js, ext_textarea_js], tw2_ace=twc.js_function('tw2_ace'), ) _ace_mode_lang_re = re.compile(r'^mode-(\S+).js$') _ace_theme_lang_re = re.compile(r'^theme-(\S+).js$') ace_modes = dict( (_ace_mode_lang_re.match(f).group(1), twc.JSLink(modname=__name__, filename=os.path.join('static/ace', f)))
initial_text = twc.Param( description='Initial text to place in the widget. Default: None', default='') wrap = twc.Param( description = 'Tag to wrap the widget with. Default: span', default='span') def prepare(self): super(DynamicTextWidget, self).prepare() # put code here to run just before the widget is displayed self.selector = self.attrs['id'].replace(':', '\\:') setup_call = twc.js_function('setupPollingDynText') class PollingDynamicTextWidget(DynamicTextWidget): data_url = twc.Param('(str) URL where JSON data should be pulled from', default=None) interval = twc.Param('(int) Polling interval in milliseconds', default=5000) def prepare(self): if self.data_url is None: raise ValueError, "DynamicTextWidget data_url parameter must be set" elif 'str' not in str(type(self.data_url)): raise ValueError, "DynamicTextWidget data_url parameter must be a string" super(PollingDynamicTextWidget, self).prepare() # put code here to run just before the widget is displayed self.add_call(setup_call(self.selector, self.data_url, self.interval))
def prepare(self): twf.InputField.prepare(self) self.safe_modify('resources') self.add_call(twc.js_function(self.bsfield)(self.compound_id, self._start_field())) self._read_opts()
import os import tw2.core as twc import tw2.forms as twf from markupsafe import Markup, escape_silent __all__ = ['CodeMirrorEditor', 'CodeMirrorDisplay'] codemirror_js = twc.JSLink( modname=__name__, filename='static/lib/codemirror.js', fromTextArea=twc.js_function('CodeMirror.fromTextArea'), ) codemirror_css = twc.CSSLink( modname=__name__, filename='static/lib/codemirror.css', ) _codemirror_css = twc.CSSLink( modname=__name__, filename='static/style.css', ) # codemirror_util_dir = twc.DirLink( # modname=__name__, # whole_dir=True, # filename='static/lib/util/', # ) #TODO: Make addons programmatically usable # codemirror_addons = dict( # (d, twc.DirLink(modname=__name__, filename=os.path.join('static/addon', d)))
dirname = Param('(string) Specify the directory path for the given ' 'file, relative to the "static" folder some ' 'substitutions are allowed. Default: %s' % \ defaults._plugin_dirname_, default=defaults._plugin_dirname_) basename = Param('(string) Specify the basename for the given file. ' 'Default: %s' % defaults._plugin_basename_, default=defaults._plugin_basename_) subdir = Param('(string) Specify the subdirectory that this link is ' 'found in. Default: %s' % defaults._plugin_subdir_, default=defaults._plugin_subdir_) @property def substitutions(self): subs = super(jQueryPluginLinkMixin, self).substitutions subs.update(dict(subdir=self.subdir)) return subs class jQueryPluginJSLink(JSLink, jQueryPluginLinkMixin): subdir = 'js' class jQueryPluginCSSLink(jQueryPluginLinkMixin, CSSLink): subdir = 'css' extension = 'css' jquery_js = jQueryJSLink() jQuery = js_function('jQuery')
import tw2.core as twc import tw2.forms as twf editarea_js = twc.JSLink( modname=__name__, filename='static/edit_area_full.js', init=twc.js_function('editAreaLoader.init') ) editarea_langs = twc.DirLink( modname=__name__, filename='static/langs', ) editarea_reg_syntaxes = twc.DirLink( modname=__name__, filename='static/reg_syntax', ) editarea_images = twc.DirLink( modname=__name__, filename='static/images', ) class EditAreaWidget(twf.TextArea): # declare static resources here # you can remove either or both of these, if not needed resources = [editarea_js] syntax = twc.Param(
import tw2.core as twc qrcode_js = twc.JSLink(modname=__name__, filename='static/qrcode.js') qrcode_css = twc.CSSLink(modname=__name__, filename='static/qrcode.css') js_draw_qr = twc.js_function('draw_qrcode')
import tw2.core as twc js_loader = twc.JSLink(modname=__name__, filename='static/dynload.js', load_js=twc.js_function("loadjs"), load_css=twc.js_function("loadcss"), #load_widget=twc.js_function('loadwidget'), load_widget=twc.js_function("load_widget"))
import urllib class TabbedContainerTabs(twc.Widget): template = 'mako:moksha.api.widgets.containers.templates.tabbedcontainer_tabs' class TabbedContainerPanes(twc.Widget): template = 'mako:moksha.api.widgets.containers.templates.tabbedcontainer_panes' tabwidget = TabbedContainerTabs(id='tabs') panewidget = TabbedContainerPanes(id='panes') jQuery = twc.js_function('jQuery') """ :Name: TabbedContainer :Type: Container """ class TabbedContainer(twf.FormField): """ :tabs: An ordered list of application tabs to display Application descriptors come from the config wrappers in moksha.lib.helpers tabs can either be in serialized string format or as a list of config wrapper objects. Using strings means you don't have to import the wrappers and predicates but can get unwieldy if there
"-- will be lost in the past!", 'start': "2012-07-02T20:08:21.634121", 'end': "2012-07-02T21:08:21.634121", 'allDay': False, }, {'title': 'long event', 'start': now + timedelta(days=7), 'end': now + timedelta(days=10), }, {'title': 'all day event', 'start': now.date(), 'allDay': True, }, ] _day_click_js = twc.js_function('function(dt){ alert(dt); }') _event_click_js = twc.js_function(''' function(calEvt, jsEvent, view) { alert('title: ' + calEvt['title'] + '\\n' + 'start: ' + calEvt['start'] + '\\n' + 'end: ' + calEvt['end'] ); } ''') class BasicCalendarWidget(FullCalendarWidget): ''' see source code for js functions and `calendar_events` ''' attrs = {'style': 'width: 100%;'}
def test_js_callback(self): eq_(str(js_callback("update_div")), "update_div") eq_(str(js_callback(js_function("foo")(1, 2, 3))), "function(){foo(1, 2, 3)}")
def test_js_callback(self): eq_(str(js_callback("update_div")), 'update_div') eq_(str(js_callback(js_function('foo')(1, 2, 3))), 'function(){foo(1, 2, 3)}')
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from tw2.core import Widget, Param, js_function from tw2.forms import TextField, TextArea from .resources import ckeditor_resources __all__ = ('CKEditorTextField', 'CKEditorTextArea') ckeditor_replace = js_function('CKEDITOR.replace') ckeditor_inline = js_function('CKEDITOR.inline') class CKEditorWidgetMixin(Widget): resources = ckeditor_resources _editor_config = Param( "low level configuration for CKEditor", default=None) inline = Param("whether to render an inline editor", default=False) def prepare(self): super(CKEditorWidgetMixin, self).prepare()
def prepare(self): super(TagifyWidget, self).prepare() self.add_call(twc.js_function("$('#"+self.selector+"').tagify")(twc.js_symbol(self.options)))
def prepare(self): super(HidingComponentMixin, self).prepare() self.safe_modify('resources') self.add_call( twc.js_function('twd_hiding_init')(self.compound_id, self.mapping))
def test_jsonified_js_function(self): obj = { 'f': js_function("$.awesome") } json = self.encode(obj) eq_(json, '{"f": $.awesome}')
import os import re import tw2.core as twc import tw2.forms as twf ace_js = twc.JSLink( modname=__name__, filename='static/ace/ace.js', edit=twc.js_function('ace.edit'), require=twc.js_function('ace.require'), ) ext_textarea_js = twc.JSLink( modname=__name__, filename='static/ace/ext-textarea.js', #Not safe for multiple widget instances per request #transformTextarea=ace_js.require('ace/ext/textarea').transformTextarea ) tw2_ace_js = twc.JSLink( modname=__name__, filename='static/tw2_ace.js', resources=[ace_js, ext_textarea_js], tw2_ace=twc.js_function('tw2_ace'), ) _ace_mode_lang_re = re.compile(r'^mode-(\S+).js$') _ace_theme_lang_re = re.compile(r'^theme-(\S+).js$') ace_modes = dict( (_ace_mode_lang_re.match(f).group(1), twc.JSLink(modname=__name__, filename=os.path.join('static/ace', f))) for f in os.listdir(os.path.join(os.path.dirname(__file__), 'static/ace'))
import re import os import tw2.core as twc from pkg_resources import ResourceManager rm = ResourceManager() tinymce_dir = twc.DirLink(modname=__name__, filename="static/tiny_mce") #tinymce_js = twc.JSLink(modname=__name__, filename='static/tinymce.js') #tinymce_css = twc.CSSLink(modname=__name__, filename='static/tinymce.css') tinymce_js = twc.JSLink(modname = __name__, filename = 'static/tiny_mce/tiny_mce_src.js', init = twc.js_function('tinyMCE.init')) def _get_available_languages(): filename_re = re.compile(r'(\w+)\.js') langs = [] locale_dir = rm.resource_filename(__name__, "static/tiny_mce/langs") for filename in os.listdir(locale_dir): match = filename_re.match(filename) if match: langs.append(match.groups(0)[0]) return langs from formencode.validators import UnicodeString, Validator from genshi.core import Markup, stripentities class MarkupConverter(UnicodeString): """A validator for TinyMCE widget.
import tw2.core as twc import tw2.forms as twf editarea_js = twc.JSLink(modname=__name__, filename='static/edit_area_full.js', init=twc.js_function('editAreaLoader.init')) editarea_langs = twc.DirLink( modname=__name__, filename='static/langs', ) editarea_reg_syntaxes = twc.DirLink( modname=__name__, filename='static/reg_syntax', ) editarea_images = twc.DirLink( modname=__name__, filename='static/images', ) class EditAreaWidget(twf.TextArea): # declare static resources here # you can remove either or both of these, if not needed resources = [editarea_js] syntax = twc.Param('Which language syntax to highlight', default='') @classmethod def post_define(cls):
def prepare(self): # put code here to run just before the widget is displayed super(CodeMirrorEditor, self).prepare() self.safe_modify('resources') options = self.default_options.copy() if self.options: options.update(self.options) try: (mode, mime) = mode_name(self.mode) self.resources.append(codemirror_modes[mode]) options['mode'] = mime or mode except KeyError: pass if self.keymap: try: self.resources.append(codemirror_keymaps[self.keymap]) options['keymap'] = self.keymap except KeyError: pass if self.theme: try: self.resources.append(codemirror_themes[self.theme]) options['theme'] = self.theme except KeyError: pass options['lineNumbers'] = bool(self.lineNumbers) if self.firstLineNumber: options['firstLineNumber'] = self.firstLineNumber if self.height_from_rows and self.rows is not None: _css = twc.CSSSource(src=u'#%s + .CodeMirror {height: %dem;}' % (self.compound_id, self.rows)) self.resources.append(_css) if self.fullscreen: self.resources.append(codemirror_addons['display']['fullscreen']) #TODO: Customizable keys self.default_options['extraKeys'] = { "F11": twc.js_callback( 'function(cm) {cm.setOption("fullScreen", !cm.getOption("fullScreen"));}' ), "Esc": twc.js_callback( 'function(cm) {if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);}' ), } try: _help_text = self.help_text except AttributeError: _help_text = u'' self.safe_modify('help_text') self.help_text = 'Press F11 when cursor is in the editor to toggle full screen editing. ' \ 'Esc can also be used to exit full screen editing.' \ + Markup('<br />') + (_help_text if _help_text else '') if self.placeholder: self.resources.append(codemirror_addons['display']['placeholder']) self.add_call( codemirror_js.fromTextArea( twc.js_function('document.getElementById')(self.compound_id), options))
def prepare(self): super(WidgetRepl, self).prepare() assert self.id, "This widget needs an id" config = dict(prefix=self.prefix) call = twc.js_function('HTTPRepl.render')('#' + self.id, config) self.add_call("jQuery(function () {%s});" % call)