Example #1
0
    def reaction(self, *connection_strings):
        # The JS version (no decorator functionality)

        if len(connection_strings) < 2:
            raise RuntimeError(
                'Component.reaction() (js) needs a function and '
                'one or more connection strings.')

        # Get callable
        if callable(connection_strings[0]):
            func = connection_strings[0]
            connection_strings = connection_strings[1:]
        elif callable(connection_strings[-1]):
            func = connection_strings[-1]
            connection_strings = connection_strings[:-1]
        else:
            raise TypeError('Component.reaction() requires a callable.')

        # Verify connection strings
        for i in range(len(connection_strings)):
            s = connection_strings[i]
            if not (isinstance(s, str) and len(s)):
                raise ValueError('Connection string must be nonempty strings.')

        # Get function name (Flexx sets __name__ on methods)
        name = RawJS("func.__name__ || func.name || 'anonymous'")
        # name = name.split(' ')[-1].split('flx_')[-1]
        nameparts = RawJS("name.split(' ')")
        nameparts = RawJS("nameparts[nameparts.length-1].split('flx_')")
        name = nameparts[-1]
        return self.__create_reaction_ob(func, name, connection_strings)
Example #2
0
def foo(a, b):
    x = RawJS('a + b')
    y = 0
    RawJS("""
    for (i=0; i<8; i++) {
        y += i * x;
    }
    """)
    RawJS("""while (y>0) {
        x += y;
        y -= 1;
    }
    """)
Example #3
0
 def beet_url(self, query):
     url = self._beet_url.text
     if not url.endswith("/"):
         url = url + "/"
     l = document.createElement("a")
     url = url + query
     url = RawJS("""url.replace(new RegExp(" , ", "g"), "/,/")""")
     l["href"] = url
     return l.href
Example #4
0
    def __create_reaction_ob(self, reaction_func, name, connection_strings):
        # Keep ref to the reaction function, see comment in create_action().

        # Create function that becomes our "reaction object"
        def reaction():
            return reaction_func.apply(self, arguments)  # arguments == events

        # Attach methods to the function object (this gets replaced)
        REACTION_METHODS_HOOK  # noqa

        # Init reaction
        that = self
        RawJS("Component.prototype._REACTION_COUNT += 1")
        reaction._id = RawJS("'r' + Component.prototype._REACTION_COUNT")
        reaction._name = name
        reaction._ob1 = lambda: that  # no weakref in JS
        reaction._init(connection_strings, self)

        return reaction
Example #5
0
    def __init__(self, *init_args, **property_values):

        RawJS('Component.prototype._COUNT += 1')
        self._id = RawJS("this.__name__ + Component.prototype._COUNT")
        self._disposed = False

        # Init some internal variables
        self.__handlers = {}  # reactions connecting to this component
        self.__pending_events = {}
        self.__anonymous_reactions = []

        # Create actions
        for i in range(len(self.__actions__)):
            name = self.__actions__[i]
            self.__create_action(self[name], name)
        # Create emitters
        for i in range(len(self.__emitters__)):
            name = self.__emitters__[i]
            self.__handlers[name] = []
            self.__create_emitter(self[name], name)
        # Create properties
        for i in range(len(self.__properties__)):
            name = self.__properties__[i]
            self.__handlers[name] = []
            self.__create_property(name)
        # Create attributes
        for i in range(len(self.__attributes__)):
            name = self.__attributes__[i]
            self.__create_attribute(name)

        # Init the values of all properties.
        prop_events = self._comp_init_property_values(property_values)

        # Apply user-defined initialization
        with self:
            self.init(*init_args)

        # Connect reactions and fire initial events
        self._comp_init_reactions()
        self._comp_init_events(prop_events)
Example #6
0
        def _init_phosphor_and_node(self):
            self.phosphor = self._create_phosphor_widget('input')
            self.node = self.phosphor.node

            RawJS('$')(self.node).datepicker()
Example #7
0
 def func(a, b):
     RawJS("""
     var c = 3;
     return a + b + c;
     """)
Example #8
0
def test_raw_js():

    with raises(TypeError):
        RawJS()
    with raises(TypeError):
        RawJS(3)

    # Empty
    r1 = RawJS('')
    assert str(r1) == ''
    assert r1.get_code() == ''
    assert r1.get_code(4) == ''
    assert '0' in repr(r1)
    assert r1.__module__.endswith(__name__)

    # Short single line
    r2 = RawJS('require("foobar")')
    assert 'require(' in repr(r2)
    assert 'require(' in str(r2)
    assert r2.get_code().startswith('require')
    assert r2.get_code(4).startswith('    require')
    assert r2.get_code(2).startswith('  require')
    assert '\n' not in r2.get_code()

    # Long single line
    r2b = RawJS('require("foobar")' * 10)
    assert 'require(' not in repr(r2b)
    assert '1' in repr(r2b)

    # Multiline, start at first line
    r3 = RawJS("""for ... {
                      yyyy  
                  }
               """)
    assert 'lines' in repr(r3)
    assert 'for ...' in str(r3)
    assert str(r3).endswith('}\n')
    assert r3.get_code().count('\n') == 3
    assert r3.get_code().startswith('for')
    assert r3.get_code(4).startswith('    for')
    assert '\n    yyyy\n' in r3.get_code(0)
    assert '\n        yyyy\n' in r3.get_code(4)

    # Multiline, exactly the same, but start at second line; same results
    r4 = RawJS("""
        for ... {
            yyyy  
        }
        """)
    assert 'lines' in repr(r4)
    assert 'for ...' in str(r4)
    assert str(r4).endswith('}\n')
    assert r4.get_code().count('\n') == 3
    assert r4.get_code().startswith('for')
    assert r4.get_code(4).startswith('    for')
    assert '\n    yyyy\n' in r4.get_code(0)
    assert '\n        yyyy\n' in r4.get_code(4)

    # Multiline, now newline at the ned
    r5 = RawJS("""
        for ... {
            yyyy  
        }""")
    assert r5.get_code().count('\n') == 2
    assert str(r5).endswith('}')
Example #9
0
 def _create_dom(self):
     global window
     node = window.document.createElement('input')
     RawJS('$')(node).datepicker()
     return node