Beispiel #1
0
 def entry(self):
     createElement = Object.get('window', 'React', 'createElement')
     if self.entry_function[0] is None:
         if self.component_object is not None: return self.component_object
         if self.component is None:
             return Object.fromString(
                 'This is the default RPython render text, override render method to get started'
             )
         if self.component.startswith(
                 'RPYJSON:') and self.component.endswith(':RPYJSON'):
             path = JSON.parse_rpy_json(self.component)
             component = Object(path).keep()
             if component.type in ['null', 'undefined']:
                 Error(
                     'Trying to get component in path %s but the type is %s'
                     % (path, component.type))
             self.component = component.toRef()
         #elif self.component.startswith('RPYJSOBJECT:') and self.component.endswith(':RPYJSOBJECT'):
         #component = Object(self.component, safe_json=True)
         #if component.type in ['null', 'undefined']:
         #   print 'Trying to get component in path %s but the type is %s' % (self.component, component.type)
         #self.component = component.toRef()
         if self.children is None or not self.children:
             return createElement.call(self.component,
                                       JSON.fromDict(self.native_props))
         return createElement.call(
             self.component, JSON.fromDict(self.native_props),
             JSON.fromList([
                 children.entry().toRef() for children in self.children
                 if children is not None
             ]) if len(self.children) > 1 else
             self.children[0].entry().toRef()
             if self.children[0] is not None else
             None)  #fromChildren(self.children, cache=False))
     #assert self.entry_function[0] is not None
     #self.rpython_count['count'] += 1
     #id = str(self.rpython_count['count'])
     id = Object.get('window', 'Math', 'random').call().toString()
     self.rpython_caches[id] = self
     self.native_props['rpython_cache_id'] = id
     if self.pure_component:
         self.props = Object.fromDict(self.native_props)
         return self.render().entry()
     if self.children is None or not self.children:
         return createElement.call(
             JSON.fromFunction(self.entry_function[0]),
             JSON.fromDict(self.native_props))
     return createElement.call(
         JSON.fromFunction(self.entry_function[0]),
         JSON.fromDict(self.native_props),
         JSON.fromList([
             children.entry().toRef() for children in self.children
             if children is not None
         ]) if len(self.children) > 1 else
         self.children[0].entry().toRef() if self.children[0] is not None
         else None)  #fromChildren(self.children))
Beispiel #2
0
    def save_grid(self, ev):
        def on_complete(req):
            if req.status == 200:
                # print(req.text)
                document["update-grid"].className = "ui right primary button"
                document.select("body")[0].toast({
                    "class":
                    "success",
                    "message":
                    "You're using the good framework !"
                })

            else:
                print("error ", req.text)

        ev.target.className = "ui loading button"
        displays = document.select(".displays")
        displays_data = {}
        for display in displays:
            displays_data[display.id] = display.innerHTML
        # print(displays_data)
        ajax.post(
            self.save_gird_url,
            data={
                "displays": JSON.stringify(displays_data),
                "grid_id": self.grid_id,
            },
            oncomplete=on_complete,
            headers={"Content-Type": "application/x-www-form-urlencoded"},
        )
Beispiel #3
0
def send_ajax_request(obj, method, data, callback):
	global user_info
	def oncomplete(req):
		callback(JSON.parse(req.text) if req.status == 200 else {'error':req.text if req.text != '' else '未能从服务器获取信息'})
	if 'user_info' not in data: data['user_info'] = user_info
	post_data = {'object':obj, 'method':method, 'data': JSON.stringify(data)}
	ajax.post('ajax', data=post_data, oncomplete=oncomplete)
Beispiel #4
0
 def handleMethod(args):
     if args is None or len(args) < 3: return
     function = args[0]
     props = args[1]
     id = args[2]
     #props = function.call()
     method = methods[id.toInteger()]
     #component = object_cache[Component][props['rpython_cache_id'].toString()]
     #component.state_function._update()
     #if component.state_function.type == 'undefined':
     component = get_component.Component.Component(
         children=[
             component_from_object(children)
             for children in props['children'].toArray()
         ] if props['children'].type == 'array' else
         [component_from_object(props['children'])]
         if props['children'].type == 'object' else [],
         react_props=props)
     component.state_function = function
     object_cache[get_component.Component][
         props['rpython_cache_id'].toString()] = component
     print get_component.Component
     props.log()
     print component
     print 'my key ' + props['rpython_cache_id'].toString()
     for key in object_cache[get_component.Component].cache:
         print key
         print object_cache[get_component.Component].cache[key]
     #component.props._update()
     #if component.props.type == 'undefined':
     #   component.props = props
     #component.init_constructor()
     Object.get('Module')['rpython_react_state_event'] = JSON.fromInteger(0)
     method.method[0](component, args=args[3:])
Beispiel #5
0
 def on_update(data, ack):
     data = JSON.parse(data)
     Game().updates = data['updates']
     Game().new_bots = data['bots']
     Game().time = data['time']
     Game().started = data['started']
     window.requestAnimationFrame(Game().draw)
     ack()
Beispiel #6
0
def change_state(task_id, new_state):
    json = {'state': new_state}

    req = ajax.Ajax()
    req.open('PATCH', f'/tasks/{task_id}', True)
    req.set_header('content-type', 'application/json')
    req.send(JSON.stringify(json))
    return req
Beispiel #7
0
def fromChildren(children, cache=True):
    refs = []
    for object in children:
        if object not in object_cache:
            object_cache[object] = None if object is None else object.entry(
            ).toRef()
        refs += [object_cache[object]]
    return JSON.fromList(refs)
Beispiel #8
0
def request(url, json, bind, method='POST'):
    """Send json data to backend."""
    req = ajax.Ajax()
    req.bind('complete', bind)
    req.open(method, url, True)
    req.set_header('content-type', 'application/json')
    req.send(JSON.stringify(json))
    return req
Beispiel #9
0
def register_task(req):
    json_response = JSON.parse(req.text)
    div = document.select_one('div.todo div.terminal-timeline')

    if json_response['urgent']:
        div.insertBefore(html_todo(json_response), div.firstChild)
    else:
        div <= html_todo(json_response)
Beispiel #10
0
def unmount_state(component):
    states = Object.get('Module', 'pyrex_state_cache')
    if states.type == 'undefined':
        Object.get('Module')['pyrex_state_cache'] = JSON.fromDict({})
        states = Object.get('Module', 'pyrex_state_cache')
    key = component.props['rpython_cache_id'].toString()
    Object('delete Module.pyrex_state_cache[%s]' %
           key)  #TODO Implement __del__ in Object
Beispiel #11
0
def get_todos(req):
    todo_states = {'todo': html_todo, 'doing': html_doing, 'done': html_done}
    json = JSON.parse(req.text)
    for todo in json:
        div = document.select_one(f'div.{todo["state"]} div.terminal-timeline')
        if todo['urgent']:
            div.insertBefore(todo_states[todo['state']](todo), div.firstChild)
        else:
            div <= todo_states[todo['state']](todo)
Beispiel #12
0
def refresh_UI(new_app_info):
    global app_info, current_activity, data_hub, user_info
    user, session_code, app, app_secret = user_info
    window.set_user_name(user)
    window.user_info = ''
    if app in ('me', 'ui', 'elt') and user != '':
        window.user_info = JSON.stringify({
            'user': user,
            'session_code': session_code,
            'app': app,
            'app_secret': app_secret
        })
    document["login"].hidden = (user == '')
    document["logout"].hidden = (user != '')

    for activity in app_info['activities']:
        document['nav-' + activity['id']].unbind('click')
    document["main-nav"].clear()
    app_info.update(new_app_info)
    for activity in app_info['activities']:
        a = html.A(activity['name'], **{
            'id': 'nav-' + activity['id'],
            'class': 'nav-link'
        })
        li = html.LI(a, **{'class': 'nav-item'})
        document["main-nav"] <= li
        a.bind('click', lambda ev: show_activity(ev.target.id))
    document["main"].clear()
    client = user_info[0]
    data_hub = DataHub(client if app_info['app'] == 'db' else '', True)
    for i, activity in enumerate(app_info['activities']):
        page = html.DIV(**{'id': 'page-' + activity['id']})
        document["main"] <= page
        if activity['ui_json'] == '':
            pass
        else:
            make_ui(JSON.parse(activity['ui_json']), page, data_hub)
        page.style.display = 'none'
    if len(app_info['activities']) > 0:
        current_activity = None
        show_activity('nav-' + app_info['activities'][0]['id'])
        data_hub.onevent('', '', '')
    else:
        window.hide_spinner_modal()
	def _set_text_data(self, text):
		from javascript import JSON
		if text is None:
			self.data = None
			self.text_data = None
		else:
			text_data_col = int(self.config['attr']['text_data_col'])
			self.text_data = text
			text = text['rows'][0][text_data_col].strip()
			if text == '':
				if 'text_data_init' not in self.config['attr']:
					window.error_toast('控件配置中缺少 text_data_init')
				else:
					text_data_init = self.config['attr']['text_data_init']
					self.data = JSON.parse(text_data_init)
					self._set_data(self.data)
			else:
				self.data = JSON.parse(text)
				self._set_data(self.data)
Beispiel #14
0
 def initial_grid(self, req):
     displays_data = JSON.parse(req.text)
     for id, img_html in displays_data.items():
         if not img_html:
             continue
         # print(img_html)
         # document[id].clear()
         document[id].innerHTML = img_html
         for child in document[id].children:
             child.bind("dragstart", self.dragstart_img)
     for clear_btn in document.select(".clear-btn"):
         clear_btn.bind("click", self.clear_display)
Beispiel #15
0
 def onload_callback(ev):
     if xhr.status == 200:
         reply = JSON.parse(xhr.responseText)
         if 'url' in reply:
             if self.event_listener is not None:
                 self.event_listener('add', reply['url'])
             window.info_toast('已上传' + str(files.length) + '个文件')
             return
         if 'error' in reply:
             window.error_toast('上传失败: ' + reply['error'])
     else:
         window.error_toast('上传失败')
Beispiel #16
0
def initial_state(component, initial=None):
    states = Object.get('Module', 'pyrex_state_cache')
    if states.type == 'undefined':
        Object.get('Module')['pyrex_state_cache'] = JSON.fromDict({})
        states = Object.get('Module', 'pyrex_state_cache')
    key = component.props['rpython_cache_id'].toString()
    state = states[key]
    if state.type == 'undefined':
        states[key] = Object('{}' if initial is None else initial,
                             safe_json=True).toRef()
        state = states[key]
    return state
Beispiel #17
0
    def render_model_choices(self, res):
        choices = JSON.parse(res.text)
        model_selector = document["model_selector"]
        model_selector.clear()
        is_fist = True
        for choice in choices:
            if is_fist:
                option = html.OPTION(choice[1], value=choice[0], selected=True)
                is_fist = False
            else:
                option = html.OPTION(choice[1], value=choice[0])

            model_selector <= option
Beispiel #18
0
	def get_data(self, data_name):
		if self.obj is None:
			if not hasattr(self.elt, data_name):
				return getattr(self.elt, data_name)
			else:
				window.error_toast('Component "%s" has no attribute "%s"' % (self.config['tag'], data_name))
		else:
			if hasattr(self.obj, 'get_data'):
				return self.obj.get_data(data_name)
			if hasattr(self.obj, 'get_data_json_text'):
				data_json = self.obj.get_data_json_text(data_name)
				if data_json is None: return None
				return JSON.parse(data_json)
			window.error_toast('Component "%s" has no function "get_data" or "get_data_json_text"' % self.config['init'])
		return None
Beispiel #19
0
 def on_initial(data):
     data = JSON.parse(data)
     Game().width = data['width']
     Game().height = data['height']
     Game().bots = data['bots']
     Game().current_field = data['field']
     Game().canvas.attrs['height'] = Game().width * PIXEL_WIDTH
     Game().canvas.attrs['width'] = Game().height * PIXEL_WIDTH
     Game().started = data['started']
     for y in range(Game().width):
         for x in range(Game().height):
             Game().ctx.fillStyle = COLORS[Game().current_field[y][x]]
             Game().ctx.fillRect(x * PIXEL_WIDTH, y * PIXEL_WIDTH,
                                 PIXEL_WIDTH, PIXEL_WIDTH)
             # Game().ctx.beginPath()
             # Game().ctx.rect(i * PIXEL_WIDTH, j * PIXEL_WIDTH, PIXEL_WIDTH, PIXEL_WIDTH)
             # Game().ctx.stroke()
     Game().draw_bots()
Beispiel #20
0
    def render_form_for_edit(self, res):
        data = JSON.parse(res.text)
        # print(data)
        if data["type"] == "uri":
            document["byURIInput"].checked = True
            document["byModelInput"].checked = False
            self.cameraFromModel.style = {"display": "none"}
            self.cameraFormURI.style = {"display": ""}
        else:
            model_selector = document["model_selector"]
            model_selector.clear()
            for choice in data.get("choices", []):
                if choice[0] == data["model_id"]:
                    option = html.OPTION(choice[1],
                                         value=choice[0],
                                         selected=True)
                else:
                    option = html.OPTION(choice[1], value=choice[0])

                model_selector <= option
Beispiel #21
0
def process_inventory(event):
    global inventory
    try:
        inventory = JSON.parse(event.target.result)   
        fusedict = {}
        mooglelist = [u['tmrId'] for u in inventory if u['id'] == moogleid]
        containerlist = [u['tmrId'] for u in inventory if u['id'] == containerid if u['tmr'] <1000]
        ownedunits = [u['id'][:-1] for u in inventory if u['id'][0] != '9' if u['tmr'] <1000 ]
        for tmrId in mooglelist:
            tmrName = weapondict[tmrId]['name']
            tmrUnit = weapondict[tmrId]['tmrUnit']
            unitName = unitdict[tmrUnit]['name']
            if tmrUnit[:-1] in ownedunits:
                    if tmrId in fusedict.keys():
                        fusedict[tmrId]['count'] += 1
                    else:
                        fusedict.update({tmrId:{'tmr':tmrName, 'unit':unitName, 'count':1, 'unitid':tmrUnit}})
            if tmrId in containerlist:
                    if tmrId in fusedict.keys():
                        fusedict[tmrId]['count'] += 1
                    else:
                        fusedict.update({tmrId:{'tmr':tmrName, 'unit':containername[code], 'count':1, 'unitid':containerid}})        
        fusesort = sorted(fusedict.items(), key = lambda item: item[1]['tmr'])
        document['results'].clear()
        table = html.TABLE(Class='table table-hover')
        tbody = html.TBODY()
        table <= tbody
        for l in fusesort:
            tbody <= html.TR([html.TD(l[1]['tmr']), html.TD('\tx' + str(l[1]['count']) + '\t'), html.TD(l[1]['unit']), html.TD(html.IMG(src='https://ffbeequip.com/img/units/unit_icon_' + l[1]['unitid'] + '.png' ) )] )
        document['results'] <= table
    except:
        alert('Error: Invalid file!')
        if 'ion-md-checkmark-circle' in filestatus.classList:
            filestatus.classList.remove('ion-md-checkmark-circle')
            filestatus.classList.add('ion-md-close-circle')
        elif 'ion-md-hourglass' in filestatus.classList:
            filestatus.classList.remove('ion-md-hourglass')
            filestatus.classList.add('ion-md-close-circle')   
 def pop(self, key, default=_UnProvided()):
     if type(default) is _UnProvided or JSON.stringify(key) in self.storage:
         return JSON.parse(self.storage.pop(JSON.stringify(key)))
     return default
 def keys(self):
     return [JSON.parse(key) for key in self.storage.keys()]
 def values(self):
     return [JSON.parse(val) for val in self.storage.values()]
def register_task(req):
    json_response = JSON.parse(req.text)
    document.select_one('div.todo div.terminal-timeline') <= html_todo(
        json_response)
Beispiel #26
0
 def setState(self):
     #if self.state_function is None: return
     self.state_function.call(JSON.fromDict({}))
Beispiel #27
0
 def oncomplete(req):
     callback(
         JSON.parse(req.text) if req.status ==
         200 else {'error': req.text if req.text != '' else '未能从服务器获取信息'})
Beispiel #28
0
def reqwComplete(request):
    global weapondict
    weapondata = JSON.parse(request.responseText)
    weapondict = {w['id']:{'name':w['name'], 'tmrUnit':w['tmrUnit']} for w in weapondata if 'tmrUnit' in w.keys()}
Beispiel #29
0
def requComplete(request):
    global unitdict
    unitdict = JSON.parse(request.responseText)
 def get(self, key, default=None):
     if JSON.stringify(key) in self.storage:
         return self.storage[JSON.stringify(key)]
     return default