예제 #1
0
파일: root.py 프로젝트: decause/moksha
    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)
예제 #2
0
    def update_params(self, d):
        super(AsynchronousJQPlotWidget, self).update_params(d)
        if not d.get('id'):
            d['id'] = 'asynch_jqplot_%s' % str(int(random() * 999))
        if not d.get('src_url'):
            raise ValueError, "AsynchronousJQPlotWidget must have a data url"
        src_url = d.get('src_url')
        url_kw = d.get('url_kw')
        if not url_kw:
            url_kw = {}
        data = d.get('data')
        if not data:
            data = [[[0,0]]]
        options = d.get('options')
        if not options:
            options = {}
        interval = d.get('interval')
        if not interval:
            interval = -1

        callback = js_callback('function (json){%s}' % self.callback_reset % d.id)
        ajres = '$.getJSON(\'%s\', %s, %s)' % (src_url, url_kw, callback)

        self.add_call(
            js_function('%s ='%d.id)(
                js_function('$.jqplot')(
                    "%s" % d.id, data, options)))

        if interval > 0 :
            self.add_call(js_function('setInterval')(ajres, interval)) 
예제 #3
0
 def update_params(self, d):
     super(JQPlotWidget, self).update_params(d)
     if not d.get('data'):
         raise ValueError, "JQPlotWidget must have data to graph"
     if not d.get('id'):
         d['id'] = 'jqplot_%s' % str(int(random() * 999))
     data = d.get('data', [])
     options = d.get('options', {})
     self.add_call(
         js_function('%s =' % d.id)(
             js_function('$.jqplot')(
                 "%s" % d.id, data, options)))
     return d
예제 #4
0
 def update_params(self, d):
     super(Epiclock, self).update_params(d)
     multi_params = dict(
         format=self.format,
         mode=self.mode,
         offset=self.offset,
         utc=self.utc,
         time=self.time,
     )
     if self.server_time:
         multi_params['time'] = js_function("new Date('%s')" %
                                            datetime.now().ctime())
     call = js_function('$("#%s").epiclock' % d.id)(multi_params)
     self.add_call(call)
예제 #5
0
	def update_params(self, d):
		super(UIDatePicker, self).update_params(d)
		if not getattr(d,"id",None):
			raise ValueError, "DatePicker is supposed to have id"

		call = js_function("$('#%s').datepicker" % d.id)()
		self.add_call(call)
예제 #6
0
	def update_params(self, d):
		super(JQTableForm, self).update_params(d)
		if not getattr(d,"id",None):
			raise ValueError, "JQTableForm is supposed to have id"
		call = js_function("$('#%s').validate" % d.id)()
		self.add_call(call)
		self.css.append(validate_css)
예제 #7
0
        def update_params(self, d):
                super(FlexiGrid, self).update_params(d)
                if not getattr(d,"id",None):
                        raise ValueError, "FlexiGrid is supposed to have id"
                if not getattr(d,"fetchURL",None):
                        raise ValueError, "FlexiGrid must have fetchURL for fetching data"
                if not getattr(d,"colModel",None):
                        raise ValueError, "FlexiGrid must have colModel for setting up the columns"

                flexi_params = dict(dataType='json',
                                    url=self.fetchURL,
                                    title=self.title,
                                    colModel=self.colModel,
                                    buttons=self.buttons,
                                    searchitems=self.searchitems,
                                    sortname=self.sortname,
                                    sortorder=self.sortorder,
                                    usepager=self.usepager,
                                    useRp=self.useRp,
                                    rp=self.rp,
                                    showTableToggleBtn=self.showTableToggleButton,
                                    width=self.width,
                                    height=self.height,
                                    resizable=self.resizable)
                print 'resizable', self.resizable
                call = js_function('$("#%s").flexigrid' % d.id)(flexi_params)
                self.add_call(call)
예제 #8
0
 def test_last_element_should_be_called(self):
     proto = js_function('$')
     call = proto('my_component').ajax
     try:
         str(call)
         assert False, 'Last element isn\'t a call, shouldn\'t work!'
     except TypeError, e:
         # just to be sure it's the type error we were expecting
         assert e.args[0] == 'Last element in the chain has to be called'
예제 #9
0
 def update_params(self, d):
     super(AutoCompleteField, self).update_params(d)
     if not getattr(d,"id",None):
         raise ValueError, "AutocompleteField is supposed to have id"
     
     if (self.fetchJSON):
         json_callback = js_callback('function(data) {$("#%s").autocomplete(data["data"]);}' % d.id)
         call = js_function('$.getJSON')(self.completionURL, json_callback)
         self.add_call(call)
     else:
         self.add_call(
         jQuery('#%s' % d.id).autocomplete(self.completionURL,dict(minChars=self.minChars,selectFirst=self.selectFirst,cacheLength=self.cacheLength,extraFields=self.extraFields))
         )
예제 #10
0
 def update_params(self, d):
     super(TextField, self).update_params(d)
     if not getattr(d, "id", None):
         raise ValueError, "Slider must have id"
     container = '%s_container' % d.id
     self.add_call(js_callback('$("#%s").slider({ \
         min: %d, max: %d, step: 1, range: false, \
         value: $("#%s").val(), \
         slide: function (event, ui) { \
             jQuery("#%s").val(ui.value);\
         } \
         })' % (container, self.min, self.max, d.id, d.id)))
     jQuery = js_function('jQuery')
     input = jQuery("#%s" % d.id)
     self.add_call(input.css("display", "none"))
예제 #11
0
 def update_params(self, d):
     super(TextField, self).update_params(d)
     if not getattr(d, "id", None):
         raise ValueError, "Slider must have id"
     container = '%s_container' % d.id
     self.add_call(
         js_callback('$("#%s").slider({ \
         min: %d, max: %d, step: 1, range: false, \
         value: $("#%s").val(), \
         slide: function (event, ui) { \
             jQuery("#%s").val(ui.value);\
         } \
         })' % (container, self.min, self.max, d.id, d.id)))
     jQuery = js_function('jQuery')
     input = jQuery("#%s" % d.id)
     self.add_call(input.css("display", "none"))
예제 #12
0
    def update_params(self, d):
        super(AjaxForm, self).update_params(d)
        if not getattr(d, "id", None):
            raise ValueError("AjaxForm is supposed to have an id")

        options = dict(
            target=('#%s' % self.target),
            beforeSubmit=self.beforeSubmit,
            success=self.success,
            url=self.action,
            type=self.type,
            dataType=self.dataType,
            clearForm=self.clearForm,
            resetForm=self.resetForm,
            timeout=self.timeout)

        call = js_function('$("#%s").ajaxForm' % d.id)(options)
        self.add_call(call)
예제 #13
0
# -*- coding: utf-8 -*-

import tw.forms as twf
import tw.forms.validators as twv

# from util import form_validator
from tw.jquery import AjaxForm
from tw.api import JSLink, js_function, JSSource, Link
from tw.jquery import jquery_js
from formencode.api import Invalid


jQuery = js_function("$")
jquery_extra_js = JSLink(modname=__name__, filename="static/js/extra.js")
# def update_option(cls, options, name, d):
#    x = d.get(name, getattr(cls, name))
#    if not x is None:
#        options[name] = x


def update_options(cls, options, d, *args):
    for name in args:
        # con None va a tomar el dafault del plugin...
        x = d.get(name, getattr(cls, name, None))
        if not x is None:
            options[name] = x
    return options


# def validar_master(form, **kw):
#    d = {}
예제 #14
0
    def update_params(self, d):
        super(JqGrid, self).update_params(d)
        grid_params = dict(url=d.url,
                           editurl=d.editurl,
                           datatype=d.datatype,
                           mtype=d.mtype,
                           colNames=d.colNames,
                           colModel=d.colModel,
                           pager=d.pager,
                           rowNum=d.rowNum,
                           rowList=d.rowList,
                           sortname=d.sortname,
                           sortorder=d.sortorder,
                           viewrecords=d.viewrecords,
                           caption=d.caption,
                           hidegrid=d.hidegrid,
                           shrinkToFit=d.shrinkToFit,
                           height=d.height,
                           width=d.width,
                           autowidth=d.autowidth,
                           toolbar=d.toolbar,
                           rownumbers=d.rownumbers,
                           toppager=d.toppager,
                           multiselect=d.multiselect,
                           multiselectWidth=d.multiselectWidth,
                           #pager
                           pginput=d.pginput,
                           pgbuttons=d.pgbuttons,
                           postData=d.postData,
                           # events
                           # http://www.trirand.com/jqgridwiki/doku.php?id=wiki:events
                           afterInsertRow = d.afterInsertRow,
                           beforeRequest = d.beforeRequest,
                           beforeSelectRow = d.beforeSelectRow,
                           gridComplete = d.gridComplete,
                           loadBeforeSend = d.loadBeforeSend,
                           loadComplete = d.loadComplete,
                           loadError = d.loadError,
                           onCellSelect = d.onCellSelect,
                           ondblClickRow = d.ondblClickRow,
                           onHeaderClick = d.onHeaderClick,
                           onPaging = d.onPaging,
                           onRightClickRow = d.onRightClickRow,
                           onSelectAll = d.onSelectAll,
                           onSelectRow = d.onSelectRow,
                           onSortCol = d.onSortCol,
                           resizeStart = d.resizeStart,
                           resizeStop = d.resizeStop,
                           serializeGridData = d.serializeGridData,
                           # tree params
                           # http://www.trirand.com/jqgridwiki/doku.php?id=wiki:treegrid
                           ExpandColClick=d.ExpandColClick,
                           ExpandColumn=d.ExpandColumn,
                           treedatatype=d.treedatatype,
                           treeGrid=d.treeGrid,
                           treeGridModel=d.treeGridModel,
                           treeIcons=d.treeIcons,
                           treeReader=d.treeReader,
                           tree_root_level=d.tree_root_level,
                           # sub grids options
                           subGrid=d.subGrid,
                           subGridUrl=d.subGridUrl,
                           subGridModel=d.subGridModel,
                           subGridWidth=d.subGridWidth,
                           # sub grids events
                           subGridRowExpanded=d.subGridRowExpanded,
                           )
        call = js_function('jQuery("#%s").jqGrid' % d.id)(grid_params)
        self.add_call(call)
        # search options documentation can be found at:
        # http://www.trirand.com/jqgridwiki/doku.php?id=wiki:singe_searching#options
        nav_call = js_function('jQuery("#%s").jqGrid' % d.id)\
                                 ('navGrid', '#%s_pager' % d.id,
                                     self.navbuttons_options,
                                     #  default settings for edit
                                     self.editbutton_options,
                                     # default settings for add
                                     self.addbutton_options,
                                     # default settings for delete
                                     self.delbutton_options,
                                     # search parameters
                                     self.search_options,
                                     # view parameters
                                     self.viewbutton_options,
                                     )

        self.add_call(nav_call)
예제 #15
0
파일: core.py 프로젝트: kamroot/mc27
 def call_getter(self,location): 
     # return dojo.require calls. This is called by the superclass 
     return map(js_function('dojo.require'), self._require) 
예제 #16
0
 def test_can_chain_calls(self):
     jQuery = js_function('jQuery')
     cb = js_callback('make_async')
     call = jQuery('a .async').click(cb).foo().bar()
     expected = 'jQuery("a .async").click(make_async).foo().bar()'
     self.failUnlessEqual(str(call), expected)
예제 #17
0
파일: flot.py 프로젝트: desarrollo1/tg2env
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Authors: Luke Macken <*****@*****.**>

from base import jquery_js
from random import random
from tw.api import Widget, JSLink, CSSLink, js_function

flot_css = CSSLink(modname=__name__, filename='static/css/flot.css')
flot_js = JSLink(modname=__name__, filename='static/javascript/jquery.flot.js')
flot_hint_js = JSLink(modname=__name__, filename='static/javascript/jquery.flot.hint.js')
hover_intent_js = JSLink(modname=__name__, filename='static/javascript/jquery.hoverIntent.js')
excanvas_js = JSLink(modname=__name__, filename='static/javascript/excanvas.js')
jQuery = js_function('$')


class FlotWidget(Widget):
    """ An attractive plotting widget.

    Using Flot, a pure Javascript plotting library for jQuery,
    this widget produces client-side graphical plots of arbitrary datasets
    on-the-fly.

    For detailed documentation on the flot API, visit the flot project 
    homepage: http://code.google.com/p/flot
    """
    template = "genshi:tw.jquery.templates.flot"
    params = {
            "data"    : "An array of data series",
예제 #18
0
파일: livegraph.py 프로젝트: lmacken/moksha
 def update_params(self, d):
     super(LiveGraphWidget, self).update_params(d)
     self.add_call(js_function('init_graph')(self.id))
예제 #19
0
파일: build.py 프로젝트: etaylor2k/RejuVu
};
"""
)


# We define the source for some JS functions we're going to interface
# External js files can be wrapped with JSLink
functions = JSSource("""
var focus_element = function (elem) {
    var elem = document.getElementById(elem);
    elem.focus(); elem.select();
    }; 
    """,
)

alert = js_function('alert')
focus_element = js_function('focus_element')


# Automatically filter out any unexpected parameters
class FilteringSchema(tw.forms.validators.Schema):
    filter_extra_fields = True
    allow_extra_fields = True


#
# - Form for new user registration -
#

class RegisterUserForm(tw.forms.TableForm):
    template = "rejuvu.templates.forms.register-user"
예제 #20
0
from moksha.lib.helpers import eval_app_config, ConfigWrapper, when_ready

moksha_ui_tabs_js = JSLink(modname='moksha', filename='public/javascript/ui/moksha.ui.tabs.js', javascript=[jquery_ui_tabs_js, ui_widget_js])

import urllib

class TabbedContainerTabs(Widget):
    template = 'mako:moksha.api.widgets.containers.templates.tabbedcontainer_tabs'

class TabbedContainerPanes(Widget):
    template = 'mako:moksha.api.widgets.containers.templates.tabbedcontainer_panes'

tabwidget = TabbedContainerTabs('tabs')
panewidget = TabbedContainerPanes('panes')

jQuery = js_function('jQuery')

"""
:Name: TabbedContainer
:Type: Container
"""
class TabbedContainer(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
           is a long list of wrappers
예제 #21
0
 def test_attr_mixed_in_chain_call(self):
     proto = js_function('$')
     iframe = js_callback('window.frames.my_iframe')
     call = proto('my_component').ajax.load_in(iframe)
     expected = '$("my_component").ajax.load_in(window.frames.my_iframe)'
     self.failUnlessEqual(str(call), expected)
예제 #22
0
from datetime import datetime
import logging
import errno

import tw
from tw.api import CSSLink, JSLink, js_function
from tw.forms import FormField, validators


__all__ = ["CalendarDatePicker", "CalendarDateTimePicker"]

setup_calendar = js_function("Calendar.setup")

log = logging.getLogger(__name__)

calendar_css = CSSLink(
    modname='tw.forms', filename='static/calendar/calendar-system.css')
calendar_js = JSLink(
    modname='tw.forms', filename='static/calendar/calendar.js')
calendar_setup = JSLink(
    modname='tw.forms', filename='static/calendar/calendar-setup.js')

class CalendarDatePicker(FormField):
    """
    Uses a javascript calendar system to allow picking of calendar dates.
    The date_format is in mm/dd/yyyy unless otherwise specified
    """
    css = [calendar_css]
    javascript = [calendar_js, calendar_setup]
    template = "tw.forms.templates.calendar"
    params = [
예제 #23
0
 def update_params(self, d):
     super(LiveGraphWidget, self).update_params(d)
     self.add_call(js_function('init_graph')(self.id))
예제 #24
0
from unittest import TestCase
from tw.core.testutil import WidgetTestCase
from tw.api import Widget, JSSource, js_function, js_callback
from tw.core.resources import dynamic_js_calls

a_js_func = js_function('a_js_func')

class TestStaticCalls(WidgetTestCase):

    class TestWidget(Widget):

        def __init__(self, *args, **kw):
            self.add_call(
                a_js_func(self.id, "This is a test")
                )

        def update_params(self, d):
            Widget.update_params(self,d)
            self.add_call(
                a_js_func(self.id, "This shouldn't be possible")
                )
        
    def test_calls_are_added(self):
        self.failUnless("This is a test" in str(self.widget._js_calls[0]))

    def XXXtest_dynamic_calls_not_possible(self):
        #XXX: This is no loner a limitation
        self.failUnlessRaises(TypeError, self.widget.update_params, {})

class TestDynamicCalls(WidgetTestCase):
    def setUp(self):
예제 #25
0
 def update_params(self, d):
     super(WidgetRepl, self).update_params(d)
     assert d.id, "This widget needs an id"
     config = dict(prefix=d.prefix)
     call = js_function('HTTPRepl.render')('#'+d.id, config)
     self.add_call("jQuery(function () {%s});" %  call)
예제 #26
0
 def update_params(self, d):
     super(WidgetRepl, self).update_params(d)
     assert d.id, "This widget needs an id"
     config = dict(prefix=d.prefix)
     call = js_function("HTTPRepl.render")("#" + d.id, config)
     self.add_call("jQuery(function () {%s});" % call)
예제 #27
0
    font-weight: bold;
    color: red;
};
""")

# We define the source for some JS functions we're going to interface
# External js files can be wrapped with JSLink
functions = JSSource(
    """
var focus_element = function (elem) {
    var elem = document.getElementById(elem);
    elem.focus(); elem.select();
    }; 
    """, )

alert = js_function('alert')
focus_element = js_function('focus_element')


# This is needed because of the way TurboGears validates as it adds
# spurious variables to the value being validated.
class FilteringSchema(Schema):
    filter_extra_fields = True
    allow_extra_fields = True


# Now the form widgets....


class AddressFieldset(ListFieldSet):
    class fields(WidgetsList):
예제 #28
0
from tw.jquery.direction import *
from tw.forms import FormField
from ui_core import jquery_ui_core_js
from ui import ui_widget_js, ui_tabs_js as jquery_ui_tabs_js

__all__ = ["jquery_ui_tabs_js"]

# declare your static resources here

## JS dependencies can be listed at 'javascript' so they'll get included
## before

jquery_ui_tabs_css    = CSSLink(modname=__name__, filename='static/css/flora.tabs.css')
#jquery_ui_tabs_js    = JSLink(modname=__name__, filename='static/javascript/ui/ui.tabs.js', javascript=[jquery_ui_core_js,jquery_direction_js, ui_widget_js])

jQuery = js_function('jQuery')

class JQueryUITabs(FormField):
    css = [jquery_ui_tabs_css
          ]
    javascript = [jquery_ui_tabs_js
                 ]
    params = ["tabdefault"]
    tabdefault__doc="0-based index of the tab to be selected on page load"
    tabdefault=0
#    include_dynamic_js_calls = True #????
    def update_params(self, d):
        super(JQueryUITabs, self).update_params(d)
        if not getattr(d,"id",None):
            raise ValueError, "JQueryUITabs is supposed to have id"
        self.add_call(jQuery("#%s" % d.id).tabs())
예제 #29
0
from datetime import datetime
import logging
import errno

import tw
from tw.api import CSSLink, JSLink, js_function
from tw.forms import FormField, validators

__all__ = [
    "CalendarDatePicker", "CalendarDateTimePicker", "calendar_js",
    "calendar_setup"
]

setup_calendar = js_function("Calendar.setup")

log = logging.getLogger(__name__)

calendar_css = CSSLink(modname='tw.forms',
                       filename='static/calendar/calendar-system.css')
calendar_js = JSLink(modname='tw.forms',
                     filename='static/calendar/calendar.js')
calendar_setup = JSLink(javascript=[calendar_js],
                        modname='tw.forms',
                        filename='static/calendar/calendar-setup.js')


class CalendarDatePicker(FormField):
    """
    Uses a javascript calendar system to allow picking of calendar dates.
    The date_format is in mm/dd/yyyy unless otherwise specified
    """