Esempio n. 1
0
    def click(self, jsFncs, profile=False, source_event=None, onReady=False):
        """
    Description:
    -----------

    Attributes:
    ----------
    :param jsFncs:
    :param profile:
    :param source_event:
    :param onReady:
    """
        if self._attrs.get('type') in ['pie']:
            tmpJsFncs = [
                "var activePoints = %s.getSegmentsAtEvent(event)" %
                self.chartId
            ]
            tmpJsFncs.append("if(activePoints.length > 0){ %s }" %
                             JsUtils.jsConvertFncs(jsFncs, toStr=True))
        else:
            tmpJsFncs = [
                "var activePoints = %s.getElementsAtEvent(event)" %
                self.chartId
            ]
            tmpJsFncs.append("if(activePoints.length > 0){ %s }" %
                             JsUtils.jsConvertFncs(jsFncs, toStr=True))
        return super(Chart, self).click(tmpJsFncs, profile)
Esempio n. 2
0
    def _events(self, event, jsFncs, source_event, profile=False, add=True):
        """
    Description:
    ------------

    Attributes:
    ----------
    :param event: String. The event type
    :param jsFncs: List or String. The JavaScript fragments
    :param source_event: String
    :param profile: Boolean or Dictionary. Optional. A flag to set the component performance storage
    :param add:
    """
        if add:
            self.onReady([
                "%s.on('%s', function (info, eventName) {%s})" %
                (source_event, event, JsUtils.jsConvertFncs(jsFncs,
                                                            toStr=True))
            ])
        else:
            self.onReady([
                "%s.off('%s', function (info, eventName) {%s})" %
                (source_event, event, JsUtils.jsConvertFncs(jsFncs,
                                                            toStr=True))
            ])
        return self
Esempio n. 3
0
  def build(self, data=None, options=None, profile=None, component_id=None):
    """
    Description:
    ------------
    Return the JavaScript fragment to refresh the component content.

    Usage::

    Attributes:
    ----------
    :param data:
    :param options: Dictionary. Optional. Specific Python options available for this component.
    :param profile: Boolean | Dictionary. Optional. A flag to set the component performance storage.
    :param component_id: String. Optional. Not used for this component.
    """
    if data is not None:
      js_convertor = "%s%s" % (self.name, self.__class__.name)
      self.page.properties.js.add_constructor(
        js_convertor, "function %s(data, options){%s}" % (js_convertor, self._js__builder__))
      profile = self.with_profile(profile, event="Builder", element_id=self.chartId)
      if profile:
        js_func_builder = JsUtils.jsConvertFncs(
          ["var result = %s(data, options)" % js_convertor], toStr=True, profile=profile)
        js_convertor = "(function(data, options){%s; return result})" % js_func_builder
      return '''
        d3.select('#%(htmlCode)s').datum(%(chartFnc)s(%(data)s, %(options)s)).transition().duration(500).call(%(chart)s); 
        nv.utils.windowResize(%(chart)s.update)''' % {
        'htmlCode': self.htmlCode, 'chartFnc': js_convertor, "data": JsUtils.jsConvertData(data, None),
        "options":  self.options.config_js(options), 'chart': self.dom.var}

    return JsUtils.jsConvertFncs([self.dom.set_var(True), self.dom.xAxis,  self.dom.yAxis,
                                  self.d3.datum(self._datasets).call(self.dom.var),
                                  "nv.utils.windowResize(function() { %s.update() })" % self.dom.var], toStr=True)[4:]
Esempio n. 4
0
 def toStr(self):
     strData = []
     for var, jsFncs in self.__js:
         strData.append("case %s: {%s; break}" % (JsUtils.jsConvertData(
             var, None), JsUtils.jsConvertFncs(jsFncs, toStr=True)))
     if self.__default is not None:
         strData.append("default: {%s}" %
                        JsUtils.jsConvertFncs(self.__default, toStr=True))
     self.__jsFncs, self.__default = [], None  # empty the stack
     return "switch (true){%s}" % ("".join(strData))
Esempio n. 5
0
    def toStr(self):
        a = JsUtils.jsConvertFncs(self.__try_jsFnc, toStr=True)
        if self.__catch_jsFnc is None:
            raise Exception("Catch must be defined")

        b = JsUtils.jsConvertFncs(self.__catch_jsFnc, toStr=True)
        if self.__fin_jsFnc is None:
            return "try{%s} catch(%s){%s}" % (a, self.error, b)

        c = JsUtils.jsConvertFncs(self.__fin_jsFnc, toStr=True)
        return "try{%s} catch(%s){%s} finally{%s}" % (a, self.error, b, c)
Esempio n. 6
0
    def findIndex(self,
                  js_funcs: Union[list, str],
                  profile: Union[dict, bool] = False):
        """
    Description:
    -----------
    The find() method returns the value of the first element in an array that pass a test (provided as a function)

    Usage::

      jsObj.console.log(jsObj.objects.array.get("MyArray").findIndex([
      jsObj.if_(jsObj.data.loop.val <= 0, [jsObj.return_(jsObj.objects.true)]),
      jsObj.return_(jsObj.objects.false)
      ]))

    Related Pages:

      https://www.w3schools.com/jsref/jsref_findindex.asp

    Attributes:
    ----------
    :param Union[list, str] js_funcs: function(currentValue, index, arr)	Required. A function to be run for each
    element in the array.
    :param Union[dict, bool] profile: Optional. A flag to set the component performance storage.

    :return: Returns the array element index if any of the elements in the array pass the test, otherwise it returns -1
    """
        js_funcs = JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)
        return JsFncs.JsFunction(
            "%s.findIndex(function(value, index, arr){%s})" %
            (self.varId, js_funcs))
Esempio n. 7
0
    def forEach(self,
                js_funcs: Union[list, str],
                value: str = "value",
                profile: Union[dict, bool] = False):
        """
    Description:
    -----------
    The forEach() method calls a provided function once for each element in an array, in order.

    Usage::

      jsObj.objects.get("MyObject").keys().forEach([
      jsObj.console.log(jsObj.data.loop.val)])

    Related Pages:

      https://www.w3schools.com/jsref/jsref_foreach.asp

    Attributes:
    ----------
    :param Union[list, str] js_funcs: A function to be run for each element in the array
    :param Optional[str] value: Optional. A value to be passed to the function to be used as its "this" value.
    :param Union[dict, bool] profile: Optional. A flag to set the component performance storage.
    """
        js_funcs = JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)
        return JsFncs.JsFunction("%s.forEach(function(%s, index, arr){%s})" %
                                 (self.varId, value, js_funcs))
Esempio n. 8
0
    def change(self,
               js_funcs,
               empty_funcs=None,
               profile=None,
               source_event=None,
               on_ready=False):
        """
    Description:
    -----------
    Javascript event triggered when the value has changed.

    Attributes:
    ----------
    :param js_funcs: List | String. Set of Javascript function to trigger on this event
    :param empty_funcs: List | String. Set of Js function to trigger if the value is empty
    :param profile: Boolean | Dictionary. Optional. A flag to set the component performance storage.
    :param source_event: String. The JavaScript DOM source for the event (can be a sug item)
    :param on_ready: Boolean. Optional. Specify if the event needs to be trigger when the page is loaded.
    """
        if not isinstance(js_funcs, list):
            js_funcs = [js_funcs]
        if empty_funcs is not None:
            if not isinstance(empty_funcs, list):
                empty_funcs = [empty_funcs]
            js_funcs.append("if (%s === ''){%s}" %
                            (self.dom.content.toStr(),
                             JsUtils.jsConvertFncs(empty_funcs, toStr=True)))
        return self.on("change", js_funcs, profile, source_event, on_ready)
Esempio n. 9
0
    def filter_(self,
                js_funcs: Union[list, str],
                js_value: Optional[str] = None,
                profile: Union[dict, bool] = False):
        """
    Description:
    -----------
    The filter() method creates an array filled with all array elements that pass a test (provided as a function)

    Related Pages:

    https://www.w3schools.com/jsref/jsref_filter.asp

    Attributes:
    ----------
    :param Union[list, str] js_funcs: A function to be run for each element in the array
    :param Optional[str] js_value: Optional. A value to be passed to the function to be used as its "this" value.
    :param Union[dict, bool] profile: Optional. A flag to set the component performance storage.
    """
        js_funcs = JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)
        if js_value is None:
            return JsFncs.JsFunction(
                "%s.filter(function(val, index, arr){%s))" %
                (self.varId, js_funcs))

        return JsFncs.JsFunction(
            "%s.filter(function(val, index, arr){%s), %s)" %
            (self.varId, js_funcs, js_value))
Esempio n. 10
0
    def build(self, data=None, options=None, profile=None, component_id=None):
        """
    Description:
    -----------

    Attributes:
    ----------
    :param data:
    :param options: Dictionary. Optional. Specific Python options available for this component.
    :param profile: Boolean | Dictionary. Optional. A flag to set the component performance storage.
    :param component_id: String. Optional. The component reference (the htmlCode).
    """
        if data is not None:
            js_convertor = "%s%s" % (self.name, self.__class__.__name__)
            self.page.properties.js.add_constructor(
                js_convertor, "function %s(data, options){%s}" %
                (js_convertor, self._js__builder__))
            profile = self.with_profile(profile,
                                        event="Builder",
                                        element_id=self.chartId)
            if profile:
                js_func_builder = JsUtils.jsConvertFncs(
                    ["var result = %s(data, options)" % js_convertor],
                    toStr=True,
                    profile=profile)
                js_convertor = "(function(data, options){%s; return result})" % js_func_builder
            return '%(chartId)s.unload({done: function() {%(chartId)s.load(%(chartFnc)s(%(data)s, %(options)s)) }})' % {
                'chartId': self.chartId,
                'chartFnc': js_convertor,
                "data": JsUtils.jsConvertData(data, None),
                "options": self.options.config_js(options)
            }

        return '%s = bb.generate(%s)' % (
            self.chartId, self.options.config_js(options).toStr())
Esempio n. 11
0
    def onerror(self,
                js_funcs: Optional[Union[list, str]],
                profile: Optional[Union[dict, bool]] = None):
        """
    Description:
    ------------
    Fired when a connection with a WebSocket has been closed because of an error,
    such as when some data couldn't be sent. Also available via the onerror property.

    Related Pages:

      https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications

    Attributes:
    ----------
    :param Optional[Union[list, str]] js_funcs: Javascript functions.
    :param Optional[Union[dict, bool]] profile: Optional. A flag to set the component performance storage.
    """
        if not isinstance(js_funcs, list):
            js_funcs = [js_funcs]
        self.page.js.onReady(
            "%s.onerror = function (event) {%s}" %
            (self._selector,
             JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)))
        return self
Esempio n. 12
0
  def then(self, js_funcs: Union[list, str], profile: Optional[Union[dict, bool]] = False):
    """
    Description:
    -----------
    As the file loading with D3 is a promise, it is possible to put events when the response is received.
    This could allow the loading of components.

    Add a post process after on the entire data.

    This function can be chained.

    Usage::

      text = page.ui.input("Italy")
        page.ui.button("Click").click([
          page.js.d3.csv(data_urls.DEMO_COUNTRY).filterCol("Country Name", text.dom.content).filterCol("Year", "2000", ">").row(
            page.js.console.log("row", skip_data_convert=True)).get(page.js.console.log("data", skip_data_convert=True))
        ])

    Attributes:
    ----------
    :param Union[list, str] js_funcs: Javascript functions.
    :param Optional[Union[dict, bool]] profile: Optional. A flag to set the component performance storage.
    """
    if not isinstance(js_funcs, list):
      js_funcs = [js_funcs]
    self._js_thens.append(
      "then(function(data) {%s; return data})" % JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile))
    return self
Esempio n. 13
0
 def click(self, jsFncs, profile=False, source_event=None, onReady=False):
     if not isinstance(jsFncs, list):
         jsFncs = []
     self._jsStyles[
         'click'] = "function(event, value){%s} " % JsUtils.jsConvertFncs(
             jsFncs, toStr=True)
     return self
Esempio n. 14
0
    def sort(self,
             js_funcs: Union[list, str],
             profile: Union[dict, bool] = False):
        """
    Description:
    -----------
    The sort() method sorts an array alphabetically:

    Usage::

      jsObj.console.log(jsObj.objects.array.new([2, 5, 12, -3], "MyArray").shift()),
      jsObj.objects.array.get("MyArray").sort()

    Related Pages:

      https://www.w3schools.com/js/js_array_sort.asp

    Attributes:
    ----------
    :param Union[list, str] js_funcs: function(currentValue, index, arr)	Required. A function to be run for each
    element in the array.
    :param Union[dict, bool] profile: Optional. A flag to set the component performance storage.

    :return: An Array object, representing the joined array
    """
        if js_funcs is not None:
            if not isinstance(js_funcs, list):
                js_funcs = [js_funcs]
            js_funcs = JsUtils.jsConvertFncs(js_funcs,
                                             toStr=True,
                                             profile=profile)
            return JsArray("%s.sort(function(a, b){%s})" %
                           (self.varId, js_funcs))

        return JsArray("%s.sort()" % self.varId, is_py_data=False)
Esempio n. 15
0
    def flatMap(self,
                js_funcs: Union[list, str],
                profile: Union[dict, bool] = False):
        """
    Description:
    -----------
    The flatMap() method first maps each element using a mapping function, then flattens the result into a new array.
    It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both
    into one method is slightly more efficient.

    Related Pages:

      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap

    Attributes:
    ----------
    :param Union[list, str] js_funcs: function(currentValue, index, arr). A function to be run for each element in the array.
    :param Union[dict, bool] profile: Optional. A flag to set the component performance storage.

    :return: An Array containing the results of calling the provided function for each element in the original array.
    """
        js_funcs = JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)
        if self.varName is not None:
            return JsArray("%s = %s" % (
                self.varId,
                JsArray(
                    "%s.flatMap(function(value, index, arr){%s; return value})"
                    % (self.varId, js_funcs),
                    is_py_data=False)),
                           is_py_data=False)

        return JsArray("%s.flatMap(function(value, index, arr){%s})" %
                       (self.varId, js_funcs),
                       is_py_data=False)
Esempio n. 16
0
  def click(self, js_funcs: Optional[Union[list, str]] = None,
            profile: Optional[Union[bool, dict]] = None, source_event: Optional[str] = None, on_ready: bool = False):
    """
    Description:
    ------------
    Add the event click and double click to the starts item.
    The Javascript function will be triggered after the change of content of the component.

    Usage::

      stars = page.ui.rich.stars(3, label="test Again")
      stars.click(page.js.console.log("test").toStr())

    Attributes:
    ----------
    :param Optional[Union[list, str]] js_funcs: The Javascript functions
    :param Optional[Union[bool, dict]] profile: Optional. A flag to set the component performance storage
    :param Optional[str] source_event: Optional. The JavaScript DOM source for the event (can be a sug item)
    :param bool on_ready: Optional. Specify if the event needs to be trigger when the page is loaded

    :return: self to allow the chains
    """
    self.css({"cursor": "pointer"})
    if js_funcs is None:
      js_funcs = []
    else:
      if not isinstance(js_funcs, list):
        js_funcs = [js_funcs]
    js_funcs = ["var data = parseInt(event.target.dataset.level)+1",
                self.build(data=JsObjects.JsObjects.get("data"), options=self._jsStyles)] + js_funcs
    str_fncs = JsUtils.jsConvertFncs(js_funcs)
    for span in self._spans:
      span.click(str_fncs, profile, source_event=source_event, on_ready=on_ready)
    return self
Esempio n. 17
0
  def click(self, js_funcs, profile=False, source_event=None, on_ready=False):
    """
    Description:
    ------------
    When a user clicks on a sparkline, a sparklineClick event is generated.
    The event object contains a property called "sparklines" that holds an array of the sparkline objects under
    the mouse at the time of the click.
    For non-composite sparklines, this array will have just one entry.

    Usage::

    Related Pages:

      https://omnipotent.net/jquery.sparkline/#interactive

    Attributes:
    ----------
    :param js_funcs: List | String. Required. Javascript functions.
    :param profile: Boolean | Dictionary. Required. A flag to set the component performance storage.
    :param source_event: String. Required. The source target for the event.
    :param on_ready: Boolean. Required. Specify if the event needs to be trigger when the page is loaded.
    """
    self.onReady("%s.bind('sparklineClick', function(event) {%s})" % (
      self.dom.jquery.varId, JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)))
    return self
Esempio n. 18
0
  def hide(self, selected_effect=None, options=None, delay=None, callback=None, profile=None):
    """
    Description:
    ------------
    Display elements using custom effects.

    Related Pages:

      https://jqueryui.com/show/

    Attributes:
    ----------
    :param selected_effect:
    :param options:
    :param delay:
    :param callback:
    :param profile:
    """
    if selected_effect is None:
      self._js.append("hide()")
    else:
      selected_effect = JsUtils.jsConvertData(selected_effect, None)
      options = JsUtils.jsConvertData(options, None)
      callback = JsUtils.jsConvertFncs(callback, toStr=True, profile=profile)
      self._js.append("hide(%s, %s, %s, %s)" % (selected_effect, options, delay, callback))
    return self
Esempio n. 19
0
    def addEventListener(self,
                         event_type: str,
                         js_funcs: Union[list, str],
                         profile: Optional[Union[dict, bool]] = None):
        """
    Description:
    ------------

    Attributes:
    ----------
    :param str event_type: The event type.
    :param Union[list, str] js_funcs: Javascript functions.
    :param Optional[Union[dict, bool]] profile: Optional. A flag to set the component performance storage.
    """
        event_type = JsUtils.jsConvertData(event_type, None)
        return JsObjects.JsVoid(
            "%(varName)s.addEventListener(%(eventType)s, function (event) {%(data)s})"
            % {
                "varName":
                self._selector,
                'eventType':
                event_type,
                "data":
                JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)
            })
Esempio n. 20
0
    def connect(self,
                script: Optional[str] = None,
                content: Optional[str] = None,
                url: Optional[str] = None):
        """
    Description:
    ------------
    Create the worker content.

    Only one of the three parameter is needed.

    .. note::

      The JavaScript content used in a web worker need to be written in a way that he can be put in one line.
      In order to be compatible with Jupyter this content need to be loaded from Js and this can only be done by
      loading a plain text in one line.

    Related Pages:

      https://www.w3schools.com/html/html5_webworkers.asp
      https://www.html5rocks.com/en/tutorials/workers/basics/

    Attributes:
    ----------
    :param Optional[str] script: Optional. The full path of the file with the javaScript content.
    :param Optional[str] content: Optional. The JavaScript content.
    :param Optional[str] url: Optional. The link of the worker module to be included to the page.
    """
        if not self.__server or content is not None:
            script_content = [
                'if(document.getElementById("js_%(id)s") != null){document.getElementById("js_%(id)s").remove()}'
                % {
                    "id": self._selector
                }, 'var wkScript = document.createElement("script")',
                'wkScript.setAttribute("id", "js_%s")' % self._selector
            ]
            if script is not None:
                with open(script) as f:
                    script_content.append('wkScript.textContent = "%s"' %
                                          f.read().strip().replace("\n", ""))
            elif url is not None:
                script_content.append('wkScript.setAttribute("src", %s)' %
                                      JsUtils.jsConvertData(url, None))
            else:
                script_content.append('wkScript.textContent = "%s"' %
                                      content.strip().replace("\n", ""))
            script_content.append('document.head.appendChild(wkScript)')
            self.page.properties.js.add_builders(
                '''
%(content)s; var blob_%(selector)s = new Blob([document.querySelector('#js_%(selector)s').textContent ], {type: "text/javascript"})
%(selector)s = new Worker(window.URL.createObjectURL(blob_%(selector)s))''' % {
                    "content": JsUtils.jsConvertFncs(script_content,
                                                     toStr=True),
                    'selector': self._selector
                })
        else:
            self.page.properties.js.add_builders("%s = new Worker('%s')" %
                                                 (self._selector, script))
        return JsObjects.JsVoid("%s = new Worker('%s')" %
                                (self._selector, script))
Esempio n. 21
0
    def reduce(self,
               js_funcs: Union[list, str],
               profile: Union[dict, bool] = False):
        """
    Description:
    -----------
    The reduce() method reduces the array to a single value.

    Usage::

      jsObj.console.log(jsObj.objects.array.get("MyArray").reduce([
      jsObj.data.reduce.val + jsObj.data.reduce.rVal,
      jsObj.return_(jsObj.data.reduce.val)]))

    Related Pages:

      https://www.w3schools.com/jsref/jsref_reduce.asp

    Attributes:
    ----------
    :param Union[list, str] js_funcs: function(currentValue, index, arr)	Required. A function to be run for each
    element in the array.
    :param Union[dict, bool] profile: Optional. A flag to set the component performance storage.

    :return: A Python / Javascript Number
    """
        from epyk.core.js.primitives import JsNumber

        js_funcs = JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)
        return JsNumber.JsNumber("%s.reduce(function (r, o, i){%s})" %
                                 (self.varId, js_funcs))
Esempio n. 22
0
    def on(self, event_type, js_funcs, profile=False):
        """
    Description:
    ------------

    Usage::

      https://www.tutorialspoint.com/socket.io/socket.io_event_handling.htm

    Attributes:
    ----------
    :param event_type:
    :param js_funcs:
    :param profile:

    :return: self to allow the chaining
    """
        if not isinstance(js_funcs, list):
            js_funcs = [js_funcs]
        event_type = JsUtils.jsConvertData(event_type, None)
        self.page.js.onReady(
            "%s.on(%s, function(data) {%s})" %
            (self._selector, event_type,
             JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)))
        return self
Esempio n. 23
0
    def every_(self,
               js_funcs: Union[list, str],
               js_value: Optional[str] = None,
               profile: Union[dict, bool] = False):
        """
    Description:
    -----------
    The every() method checks if all elements in an array pass a test (provided as a function).
    Data Structure used in this method is like obj(val, index, array)

    Usage::

      Related Pages:

      https://www.w3schools.com/jsref/jsref_every.asp

    Attributes:
    ----------
    :param Union[list, str] js_funcs: A function to be run for each element in the array
    :param Optional[str] js_value: Optional. A value to be passed to the function to be used as its "this" value.
    :param Union[dict, bool] profile: Optional. A flag to set the component performance storage.
    """
        js_funcs = JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)
        if js_value is None:
            return JsFncs.JsFunction(
                "%s.every(function(val, index, arr){%s})" %
                (self.varId, js_funcs))

        return JsFncs.JsFunction(
            "%s.every(function(val, index, arr){%s}, %s)" %
            (self.varId, js_funcs, js_value))
Esempio n. 24
0
  def loadHtml(self, htmlObjs, append=False):
    """
    Description:
    ------------
    Load during a Javascript event a component within the one using this method.
    This cannot be tested during the Python execution and should be tested in the browser.

    Tip: It is possible to add a break point to debug in the browser by adding

    Usage::

      d = rptObj.ui.div().css({"border": "1px solid black"})
    b = rptObj.ui.button("test")
    b.click([
      rptObj.js.console.debugger,
      d.dom.loadHtml(rptObj.ui.texts.label("test label").css({"color": 'blue', 'float': 'none'}))
    ])

    Attributes:
    ----------
    :param htmlObjs: List. The different HTML objects to be added to the component
    :param append: Boolean. Mention if the component should replace or append the data

    :return: The Javascript string to be added to the page
    """
    if not isinstance(htmlObjs, list):
      htmlObjs = [htmlObjs]

    jsFncs = []
    for i, h in enumerate(htmlObjs):
      h.options.managed = False
      jsFncs.append(self._report.js.objects.new(str(h), isPyData=True, varName="obj_%s" % i))
      jsFncs.append(self.innerHTML(self._report.js.objects.get("obj_%s" % i), append=append).r)
    return JsUtils.jsConvertFncs(jsFncs, toStr=True)
Esempio n. 25
0
    def enter(self, jsFncs, profile=False, source_event=None, onReady=False):
        """
    Description:
    -----------
    Add an javascript action when the key enter is pressed on the keyboard

    Example
    htmlObj.enter(" alert() ")

    Attributes:
    ----------
    :param jsFncs: String or List. The Javascript functions
    :param profile: Boolean or Dictionary. Optional. A flag to set the component performance storage
    :param source_event: String. The JavaScript DOM source for the event (can be a sug item)
    :param onReady: Boolean. Optional. Specify if the event needs to be trigger when the page is loaded

    :return: The python object itself
    """
        self.click(jsFncs)
        if not isinstance(jsFncs, list):
            jsFncs = [jsFncs]
        return self.on("keydown", [
            "if (event.keyCode  == 13) {event.preventDefault(); %(jsFnc)s } " %
            {
                "jsFnc": JsUtils.jsConvertFncs(jsFncs, toStr=True)
            }
        ],
                       profile=profile,
                       source_event=source_event,
                       onReady=onReady)
Esempio n. 26
0
 def toStr(self):
     js_n_funcs = JsUtils.jsConvertFncs(self.__js_funcs,
                                        toStr=True,
                                        profile=self.profile)
     js_iter = JsUtils.jsConvertData(self.__js_it, None)
     return "for(var %s %s %s){%s}" % (self.var, self.options['type'],
                                       js_iter, js_n_funcs)
Esempio n. 27
0
    def __init__(self,
                 condition: str,
                 js_funcs: Union[list, str],
                 context: Optional[primitives.PageModel] = None,
                 profile: Optional[Union[dict, bool]] = False):
        """
    Description:
    ------------
    Create a JavaScript If statement.

    Usage::

      JsIf.JsIf(self.input.dom.hasClass("fa-check"), jsFncsTrue)

    Attributes:
    ----------
    :param str condition: The Javascript condition. Can be a JsBoolean object.
    :param Union[list, str] js_funcs: Optional. The Javascript functions.
    :param Optional[primitives.PageModel] context: Optional. Meta data concerning the context.
    :param Optional[Union[dict, bool]] profile: Boolean. Optional. A flag to set the component performance storage.
    """
        self._context = context
        js_funcs = JsUtils.jsConvertFncs(js_funcs, False, profile=profile)
        if hasattr(condition, "toStr"):
            condition = condition.toStr()
        self._js = [(condition, js_funcs)]
        self.__js_else = None
Esempio n. 28
0
    def click(self,
              js_funcs: Union[list, str],
              profile: Optional[Union[bool, dict]] = None,
              source_event: str = None,
              on_ready: bool = False):
        """
    Description:
    ------------
    Add a click event on a specific step.

    Attributes:
    ----------
    :param Union[list, str] js_funcs: Javascript functions.
    :param Optional[Union[bool, dict]] profile: Optional. A flag to set the component performance storage.
    :param str source_event: Optional. The source target for the event.
    :param bool on_ready:
    """
        return JsObjects.JsObjects.get(
            '%(src)s.style.cursor = "pointer"; %(src)s.addEventListener("click", function(){%(fncs)s})'
            % {
                "src":
                source_event or self.varName,
                "fncs":
                JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)
            })
Esempio n. 29
0
    def inline(self,
               func_name: str,
               js_funcs: Union[str, list],
               pmts: dict = None):
        """
    Description:
    ------------
    Create a name function which can be then called later.

    Related Pages:

      https://www.w3schools.com/js/js_function_definition.asp

    Attributes:
    ----------
    :param str func_name: The function name.
    :param Union[str, list] js_funcs: Javascript functions.
    :param dict pmts: Optional. The function parameters.

    :return: The function name which can be used in the Javascript
    """
        self._js_src.setdefault('functions', {})[func_name] = {
            'content': JsUtils.jsConvertFncs(js_funcs, toStr=True),
            'pmt': pmts
        }
        return func_name
Esempio n. 30
0
    def on(self,
           event: str,
           js_funcs: Union[list, str],
           profile: Optional[Union[bool, dict]] = None,
           source_event: Optional[str] = None,
           on_ready: bool = False):
        """
    Description:
    -----------
    Javascript generic events of the items in the menu.

    Attributes:
    ----------
    :param str event: The JavaScript event.
    :param Union[list, str] js_funcs: The Javascript functions.
    :param Optional[Union[bool, dict]] profile: Optional. A flag to set the component performance storage.
    :param Optional[str] source_event: Optional. Override the source component on which the component is defined.
    :param bool on_ready: Optional. Specify if the event needs to be trigger when the page is loaded.
    """
        if not isinstance(js_funcs, list):
            js_funcs = [js_funcs]
        self._events.append(
            "%s.addEventListener('%s', function (event) {%s})" %
            (source_event or self.component_id, event,
             JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)))
        if on_ready:
            self.page.body.onReady([
                self.page.js.getElementById(
                    self.component_id).dom.events.trigger(event)
            ])
        return self.container