def set_icon(self, Surface=None): link = document.createElement("link") link.type = "image/x-icon" link.rel = "shortcut icon" link.href = Surface document.get(selector='head')[0] <= link return None
def reset_character(ev): grind_table_state['checked'] = set() for char in grind_table_state['characters']: grind_table_state['characters'][char] = char_dict.copy() grind_table_state['arti_check'].add(char) grind_table_state['artifacts'] = set() for val in grind_table_state['total']: grind_table_state['total'][val] = 0 for elt in doc.get(selector='input[type=checkbox]'): if 'char_select' in elt.attrs['class']: doc[elt.id].checked = False else: doc[elt.id].checked = True for elt in doc.get(selector='select'): elt.selectedIndex = 0 for elt in doc.get(selector='TR[data-id]'): elt.attrs['class'] = 'unchecked' for elt in doc.get(selector='.saved_arti'): del doc[elt.id] for key in storage.keys(): if key.startswith(storage_key) and not key.endswith('-user'): del storage[key] calculate_change() update_visible()
def create_script_tag(src): _fp, _, _=urllib.request.urlopen(src) _data=_fp.read() _tag=document.createElement('script') _tag.type="text/javascript" _tag.text=_data document.get(tag='head')[0].appendChild(_tag)
def create_script_tag(src): _fp, _, _ = urllib.request.urlopen(src) _data = _fp.read() _tag = document.createElement('script') _tag.type = "text/javascript" _tag.text = _data document.get(tag='head')[0].appendChild(_tag)
def gen_table(): h_vals = [] for _elt in doc.get(selector='.header'): if _elt.checked: h_vals.append(data[0].index(_elt['data-id'])) f_vals = [] for _elt in doc.get(selector='.flag_val'): if _elt.checked: f_vals.append(_elt['data-id']) t_data = [[y for c, y in enumerate(data[0]) if c in h_vals]] t_data.extend([[y for c, y in enumerate(x) if c in h_vals] for x in data[1:] if x[0] in f_vals and x[-1] in f_vals]) return t_data
def _toggle(e): selector = '.{}{}-{}'.format(selector_prefix, ns_name, service_name) elems = doc.get(selector=selector) for elem in elems: if 'service-details-header' in elem.id or 'current-item' in elem.class_name: self._toggle(None, '#{}'.format(elem.id))
def blit(self, source, dest, area=None, special_flags=0): #if area is None and isinstance(source, str): # _img = JSConstructor(window.Image)() # _img.src = source # def img_onload(*args): # self._context.drawImage(_img, dest[0], dest[1]) # _img.onload=img_onload # _img.width, _img.height global _canvas_id if _canvas_id is None: try: _canvas_id=document.get(selector='canvas')[0].getAttribute('id') except: pass if self._canvas.id == _canvas_id: self._canvas.width=self._canvas.width if area is None: #lets set area to the size of the source if isinstance(source, Surface): area=[(0, 0), (source.canvas.width, source.canvas.height)] if isinstance(source, Surface): _ctx=source.canvas.getContext('2d') _subset=_ctx.getImageData(area[0][0],area[0][1], area[1][0], area[1][1]) # we want just a subset of the source image copied self._context.putImageData(_subset, dest[0], dest[1]) #print(dest[0], dest[1], _subset.width, _subset.height) return Rect(dest[0], dest[1], dest[0]+_subset.width, dest[1]+_subset.height)
def loadButtons(): global codepage HEAD_HTML = '<tr><th style="padding:3px"></th>\n{}\n</tr>' document["buttons"].html = HEAD_HTML.format('\n'.join(map( '<th style="padding:3px">_{0:1x}</th>'.format, range(16)))) BUTTON_HTML = '<tr>\n<th style="padding:3px">{0:1x}_</th>\n{1}</tr>' for i in range(16): r = '' for j in range(16): if i*16+j >= len(codepage): break ch = codepage[i*16+j] ch = "NUL" if ch == "\x00" else "SP" if ch == " " else ch r += ('<td><button type="button" class="btn btn-xs btn-default"' ' style="font-family:monospace" style="padding:3px">{}' '</button></td>\n').format(ch) document["buttons"].html += BUTTON_HTML.format(i, r) for btn in document.get(selector='button'): btn.bind('click', addtext) document["clear"].unbind('click') document["clear"].bind('click', clear)
def send(): req = ajax.ajax() req.bind('complete',on_complete) req.open(document['req_method'].value, '/ajax', True) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send({'param_name': 'param_value'})
def blur(ev): # check cells with formulas for cell in document.get(selector="td"): if cell.text.startswith("="): formula = cell.text[1:] pattern = RegExp("([A-Z]+)([0-9]+)", "g") print(formula, String(formula).replace(pattern, 'cell("$1$2")'))
def mark_cells(self): # column number col = self.col_num() rows = document.get(selector="tr") for row in rows[1:]: row.childNodes[col].classList.add("column-select")
def _switch(e): # Switch everything off .. for detail in header_details: id = '#service-details-{}-{}-{}'.format( detail, ns_name, service_name) elems = doc.get(selector=id) for elem in elems: classes = elem.class_name.split(' ') if 'current-item' in classes: classes.remove('current-item') elem.class_name = ' '.join(classes) self._toggle(None, id, False) # .. and switch on only the required one. current_id = 'service-details-{}-{}-{}'.format( current, ns_name, service_name) _current = doc[current_id] self._toggle(None, '#{}'.format(current_id), True) classes = _current.class_name.split(' ') classes.append('current-item') _current.class_name = ' '.join(classes) # Don't forget about cancelling the default handler e.preventDefault()
def _toggle(e): self._toggle(e, '.tr-service-ns-{}'.format(ns_name), True) # Iterate as long as we don't hit upon another header for elem in doc.get(selector='#tr-ns-{} ~ tr'.format(ns_name)): if 'tr-ns' in elem.id: break selector = '.service-details-toggle-{}-{}'.format( ns_name, elem.id.replace('tr-service-', '')) elems = doc.get(selector=selector) for elem in elems: if 'service-details-header' in elem.id or 'current-item' in elem.class_name: self._toggle(None, '#{}'.format(elem.id))
def on_submit(event): event.preventDefault() name = document['org_name_field'].value boards = [o.value for o in input2 if hasattr(o, 'selected') and o.selected] users = [o.value for o in input3 if hasattr(o, 'selected') and o.selected] owner = getApiLink('users', document['body'].__getattribute__('data-userid')) if name and boards and users: data = { 'name': name, 'boards': boards, 'users': users, 'owner': owner } def on_complete(response): if response.status == 201: hide_modal() else: alert(response.text) req2 = ajax.ajax() req2.bind('complete', on_complete) req2.open('POST', '/api/organizations/?format=json', True) req2.set_header('content-type', 'application/x-www-form-urlencoded') req2.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req2.send(data)
def loadButtons(): global codepage HEAD_HTML = '<tr><th style="padding:3px"></th>\n{}\n</tr>' document["buttons"].html = HEAD_HTML.format('\n'.join( map('<th style="padding:3px">_{0:1x}</th>'.format, range(16)))) BUTTON_HTML = '<tr>\n<th style="padding:3px">{0:1x}_</th>\n{1}</tr>' for i in range(16): r = '' for j in range(16): if i * 16 + j >= len(codepage): break ch = codepage[i * 16 + j] ch = "NUL" if ch == "\x00" else "SP" if ch == " " else ch r += ('<td><button type="button" class="btn btn-xs btn-default"' ' style="font-family:monospace" style="padding:3px">{}' '</button></td>\n').format(ch) document["buttons"].html += BUTTON_HTML.format(i, r) for btn in document.get(selector='button'): btn.bind('click', addtext) document["clear"].unbind('click') document["clear"].bind('click', clear)
def blit(self, source, dest, area=None, special_flags=0): #if area is None and isinstance(source, str): # _img = JSConstructor(window.Image)() # _img.src = source # def img_onload(*args): # self._context.drawImage(_img, dest[0], dest[1]) # _img.onload=img_onload # _img.width, _img.height global _canvas_id if _canvas_id is None: try: _canvas_id=document.get(selector='canvas')[0].getAttribute('id') except: pass if self._canvas.id == _canvas_id: self._canvas.width=self._canvas.width if area is None: #lets set area to the size of the source if isinstance(source, Surface): area=[(0, 0), (source.canvas.width, source.canvas.height)] if isinstance(source, Surface): _ctx=source.canvas.getContext('2d') _subset=_ctx.getImageData(area[0][0],area[0][1], area[1][0], area[1][1]) # we want just a subset of the source image copied self._context.putImageData(_subset, dest[0], dest[1]) #print(dest[0], dest[1], _subset.width, _subset.height) return Rect(dest[0], dest[1], dest[0]+_subset.width, dest[1]+_subset.height)
def blur(self, ev): # check cells with formulas for cell in document.get(selector="td"): if cell.text.startswith("="): formula = cell.text[1:] pattern = RegExp("([A-Z]+)([0-9]+)", "g") print(formula, String(formula).replace(pattern, 'cell("$1$2")'))
def __init__(self, container): self._id = document.get(id=container)[0] setattr(self._id, 'id', '') setattr(window, '__context', {}) setattr(getattr(window, '__context'), 'glowscript_container', self._id.elt)
def mark_cells(self): # column number col = self.col_num() rows = document.get(selector="tr") for row in rows[1:]: row.childNodes[col].classList.add("column-select")
def on_submit(event): assignee = None if document['assignee_field'].value == 'None' \ else document['assignee_field'].value deadline = '' if document['deadline_field'].value == '' \ else document['deadline_field'].value + 'T01:01' difficulty = None if document['difficulty_field'].value == '---' \ or document['difficulty_field'].value not in ('easy', 'intermediate', 'hard') \ else document['difficulty_field'].value colours = [] for checked_colour in document.get(selector='a.colour-btn.checked'): colours.append(checked_colour.id[-1]) data = { 'id': document['id_field'].value, 'name': document['name_field'].value, 'description': document['description_field'].value, 'assignee': assignee, 'deadline': deadline, 'difficulty': difficulty, 'colours': ','.join(colours) } def taskUpdated(req): data = loads(req.text) if 'id' in data: # zapisalo sie poprawnie document['task_' + str(data['id'])].clear() data['colours'] = data['colours'].split(',') if data['colours'] else [] addColours(data, document['task_' + str(data['id'])]) document['task_' + str(data['id'])] <= H3(data['name'], **{'data-task-id': data['id']}) hide_modal() else: for field, errors in data.items(): error_field_name = field + '_error' for error in errors: document[error_field_name] <= error for error_field in document.get(selector='.panel.error'): error_field.clear() a = ajax.ajax() a.open('PATCH', '/api/tasks/' + str(data['id']) + '/?format=json') a.bind('complete', taskUpdated) a.set_header('content-type', 'application/x-www-form-urlencoded') a.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) a.send(data) return False
def bind(cls): def ev_handler(ev): ev.preventDefault() ev.stopPropagation() cls.show(ev.currentTarget.href) for link in document.get(selector="a.glyphicon-question-sign"): link.bind("click", ev_handler)
def archiveList(event): lists_id = event.target.parent.parent.data_list_id console.log(lists_id) parent_selector = '#tasks_for_list_{0}'.format(lists_id) tasks_ids = [t.elt.id.strip('task_') for t in document.get(selector=parent_selector + ' .taskDiv')] for task_id in tasks_ids: _archiveTask(task_id) _archiveList(lists_id)
def _toggle(e): selector = '.{}{}-{}'.format(selector_prefix, ns_name, service_name) elems = doc.get(selector=selector) for elem in elems: if 'service-details-header' in elem.id or 'current-item' in elem.class_name: self._toggle(None, '#{}'.format(elem.id)) # Prevent href="#" navigation causing browser to scroll to top of page. e.preventDefault()
def _archiveList(lists_id): link = getApiLink('boardlists', lists_id) req = ajax.ajax() req.open('DELETE', link, False) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send() document['tasks_for_list_' + lists_id].parent.style.display = 'none'
def get_pos(): global _canvas if _canvas is None: _c=document.get(selector='canvas') if len(_c) > 0: _canvas=_c[0] console.log(_canvas.id) _canvas.mousemove=_getMousePosition return _mouse_x, _mouse_y
def reset_inventory(ev): for val in grind_table_state['user']: grind_table_state['user'][val] = 0 for elt in doc.get(selector='input[type=number]'): elt.value = 0 for key in storage.keys(): if key.startswith(storage_key) and key.endswith('-user'): del storage[key] calculate_change()
def _archiveTask(task_id): link = getApiLink('tasks', task_id) req = ajax.ajax() req.open('DELETE', link, False) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send() del document['task_' + task_id]
def get_pos(): global _canvas if _canvas is None: _c = document.get(selector='canvas') if len(_c) > 0: _canvas = _c[0] console.log(_canvas.id) _canvas.mousemove = _getMousePosition return _mouse_x, _mouse_y
def __init__(self, container): glowid = GLOWID + container if glowid in document: document[container].remove() document[container] <= html.DIV(Id=glowid, Class="glowscript") self._id = document.get(id=glowid)[0] # setattr(self._id, 'id', '') setattr(window, '__context', {}) setattr(getattr(window, '__context'), 'glowscript_container', self._id.elt)
def save_state(ev): if '-' in ev.target.id: key, char = ev.target.id.split('-') else: key = ev.target.id char = '' if ev.target.type == 'checkbox' and 'char_select' in ev.target.attrs[ 'class']: binstate = ev.target.checked newstate = 'checked' if binstate else 'unchecked' for elt in doc.get( selector=f'TR[data-id="{ev.target.attrs["data-id"]}"]'): elt.attrs['class'] = newstate if ev.target.checked: grind_table_state['checked'].add(ev.target.id.split('-')[1]) set_storage(ev.target.id, 'checked') else: grind_table_state['checked'].discard(ev.target.id.split('-')[1]) del_storage(ev.target.id) calculate_change() if doc['selected'].value != 'All': update_visible() elif ev.target.type == 'checkbox': if ev.target.checked: grind_table_state['arti_check'].add(ev.target.id.split('-')[1]) del_storage(ev.target.id) else: grind_table_state['arti_check'].discard(ev.target.id.split('-')[1]) set_storage(ev.target.id, 'unchecked') if char in grind_table_state['checked']: calculate_change() elif ev.target.type == 'select-one': if ev.target.selectedIndex: set_storage(ev.target.id, f"select-{ev.target.value}") else: del_storage(ev.target.id) if char: grind_table_state['characters'][char][key] = int( ev.target.value) if ev.target.value.isnumeric( ) else ev.target.value if char in grind_table_state['checked']: calculate_change() else: update_visible() elif ev.target.type == 'number': if not ev.target.value.isnumeric() or int(ev.target.value) < 0: ev.target.value = 0 else: ev.target.value = int(ev.target.value) grind_table_state['user'][key] = int(ev.target.value) set_storage(ev.target.id, ev.target.value) calculate_change() else: print(f"Unhandled element type for storage: {ev.target.type}")
def search_chars(ev): search_terms = ev.target.value.lower().split() for el in doc.get(selector="[data-id^=check]"): if all(x in el.attrs['data-id'][6:] for x in search_terms): print(el.attrs['data-id'][6:]) if 'hidden' in el.attrs: del el.attrs['hidden'] else: el.attrs['hidden'] = '' if not doc['keywords'].value: update_visible()
def star_toggle(event): mark = 'star_empty.png' in event.target.src set_star(mark) selected = [opt for opt in document['boardSelect'] if hasattr(opt, 'value') and opt.value == document['boardSelect'].value].pop() selected.data_star = 'true' if mark else 'false' req = ajax.ajax() req.open('PATCH', getApiLink('boards', selected.value) + '?format=json', True) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send({'star': mark})
def load(sheet_name=None): global current_cell_info, menu_file panel = document['panel'] cell_editor = html.DIV("A", style=dict(width="25%", padding="5px", marginBottom="20px", height="1.5em"), Id="current", contentEditable="true", Class="selected") cell_editor.bind('click', enter_editor) cell_editor.bind('keydown', editor_keydown) cell_editor.bind('keyup', update_from_editor) panel <= cell_editor t = html.TABLE(Id="sheet_table") srow = -1 rows, cols = 20, 20 col_widths = [100 for i in range(rows)] line = html.TR() line <= html.TH() for i in range(cols): col_name = chr(65 + i) line <= ColumnHead(col_name, Class="col-head", style={'min-width': '%spx' % col_widths[i]}) t <= line for i in range(rows * cols): row, column = divmod(i, cols) if row > srow: line = html.TR() line <= RowHead(row + 1, Class="row-head") t <= line srow = row cell = html.TD(contentEditable="true", style=dict(padding='2px')) cell.bind("click", select) cell.bind("focus", focus) cell.bind("keyup", keyup) cell.bind("blur", blur) cell.info = {'entry': ''} line <= cell panel <= html.DIV(t, style=dict(float='left')) for cell in document.get(selector="th.row-head"): cell.bind("mousedown", select_row) t.get(selector='TD')[0].dispatchEvent(window.MouseEvent.new("click"))
def chan_edit_favorite(event): enable_bool = bool(int(document["favorite_button"].value)) for element in document.get(selector='input[type="checkbox"]'): if element.name == "favorite": element.checked = enable_bool element.value = int(enable_bool) if not enable_bool: document["favorite_button"].value = "1" document["favorite_button"].text = "Favorite All" else: document["favorite_button"].value = "0" document["favorite_button"].text = "Unfavorite All"
def chan_edit_enable(event): enable_bool = bool(int(document["enable_button"].value)) for element in document.get(selector='input[type="checkbox"]'): if element.name == "enabled": element.checked = enable_bool element.value = enable_bool if not enable_bool: document["enable_button"].value = "1" document["enable_button"].text = "Enable All" else: document["enable_button"].value = "0" document["enable_button"].text = "Disable All"
def deleteBoard(event): selected = [opt for opt in document['boardSelect'] if hasattr(opt, 'value') and opt.value == document['boardSelect'].value].pop() new_opts = [opt for opt in document['boardSelect'] if hasattr(opt, 'value') and opt.value != document['boardSelect'].value] document['boardSelect'].clear() for opt in new_opts: document['boardSelect'] <= opt loadListsForSelectedBoard() updateStar() req = ajax.ajax() req.open('POST', '/board_delete', True) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send({'boards_id': selected.value})
def generate_query(ev): league = leagues[doc['league'].selectedIndex] set_storage('league', league) base = bases[doc['base'].selectedIndex] set_storage('base', base) for _f in saved_states: if doc[_f].checked: set_storage(_f, "T") else: set_storage(_f, "") url_api = f'https://www.pathofexile.com/trade/search/{league}?q=' dps = {} for elt in doc.get(selector='input[type="number"].dps_val'): dps[elt.id] = [float(elt.value)/float(elt.getAttribute("data-normal")), float(elt.value)] dps['extrarandom'] = [(dps['extrafire'][0] + dps['extracold'][0] + dps['extralightning'][0]) / 3, (dps['extrafire'][1] + dps['extracold'][1] + dps['extralightning'][1]) / 3] selections = set() for elt in doc.get(selector='input[type="checkbox"]'): if elt.checked: selections.add(elt.id) mjson_max = max(mjson) if mjson_max != current_version: for mod in mjson[mjson_max]: if mod['name'] not in dps: dps[mod['name']] = [0, 0] querystring, count, culled = gensearchparams(dps, selections, base) doc['culled'].text = '' if culled: mystr = '' for _x in [BR() + x for x in culled]: mystr += _x doc['culled'] <= BR() + f'{len(culled)} mods were culled from query.' + BR() + mystr doc["query"].href = url_api + querystring doc["modcount"].text = count doc["414bypass"].value = querystring doc["query"].style.display = "inline" doc["notice"].style.display = "inline" doc["414by"].style.display = "inline"
def on_drop(ev): ev.preventDefault() task_element_id = ev.dataTransfer.getData('text') element = document[task_element_id] task_id = task_element_id.split('_')[-1] target = ev.target if not hasattr(ev.target, 'class_name') or ev.target.class_name != 'tasksContainer': if ev.target.class_name == 'taskDiv' or ev.target.class_name == 'newTaskInput': target = ev.target.parent elif ev.target.class_name == 'task_name_header': target = ev.target.parent.parent elif ev.target.class_name == 'newTaskInput': target = ev.target.parent else: return dragee_pos = ev.clientY positions_elements = {dragee_pos: element} new_elements_positions = [dragee_pos] for el in target.get(selector='.taskDiv'): pos = el.top if el.top != dragee_pos else el.top - 1 positions_elements[pos] = el new_elements_positions.append(pos) new_elements_positions.sort() tasks_positions = {} for i, pos in enumerate(new_elements_positions, 1): el = positions_elements[pos] target <= el tasks_positions[el.__getattribute__('data-task-id')] = i def set_new_positions(ev): a = ajax.ajax() a.open('POST', '/update_tasks_positions', True) a.set_header('content-type', 'application/x-www-form-urlencoded') a.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) a.send({'updates': dumps(tasks_positions)}) a = ajax.ajax() a.open('PATCH', getApiLink('tasks', task_id) + '?format=json') a.bind('complete', set_new_positions) a.set_header('content-type', 'application/x-www-form-urlencoded') a.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) a.send({'id': task_id, 'board_list': getApiLink('boardlists', target.data_list_id)})
def check_email(event): def callback(response): r = loads(response.text) if r['success']: document.get(name='registerBtn')[0].disabled = False else: document.get(name='registerBtn')[0].disabled = True given_email = document['id_email_address'].value if given_email: req = ajax.ajax() req.bind('complete', callback) req.open('POST', '/check_email', True) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send({'email': given_email})
def render(event): for comp_cls in Register.reg: pprint("Initializing elements", comp_cls) elems = document.get(selector=comp_cls.tag) pprint("Elements found:", len(elems)) for elem in elems: try: # If has rd then the component is already initialized if elem.rd: continue except: pass rootcomp = comp_cls(elem) rootcomp.root = rootcomp rootcomp.mount()
def update_visible(): if not doc['keywords'].value: c = doc['selected'].value e = doc['element'].value w = doc['weapon'].value for el in doc.get(selector="#character_list .body tr[data-id]"): if c in ['any', el.attrs['class'] ] and (e in ['any', el.attrs['data-color']] or (el.attrs['data-color'] == 'multi' and e in ['anemo', 'geo'])) and w in [ 'any', el.attrs['data-weapon'] ]: if 'hidden' in el.attrs: del el.attrs['hidden'] else: el.attrs['hidden'] = ''
def setSelectedBackgroundModal(selected_id): document['background-1'].class_name = document['background-1'].class_name = 'background-select-image' document['background-2'].class_name = document['background-2'].class_name = 'background-select-image' document['background-3'].class_name = document['background-3'].class_name = 'background-select-image' document['background-4'].class_name = document['background-4'].class_name = 'background-select-image' document['background-{0}'.format(selected_id)].class_name += ' selected' selected = [opt for opt in document['boardSelect'] if hasattr(opt, 'value') and opt.value == document['boardSelect'].value].pop() selected.data_background = selected_id document['body'].class_name = 'background-{0}'.format(selected_id) req = ajax.ajax() req.open('POST', '/bgchange', True) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send({'background': selected_id, 'boards_id': selected.value})
def render(event): for comp_cls in Register.reg: pprint("Initializing elements", comp_cls) elems = document.get(selector=comp_cls.tag) pprint("Elements found:", len(elems)) for elem in elems: try: # If has rd then the component is already initialized if elem.rd: continue except: pass rootcomp = comp_cls(elem) rootcomp.root = rootcomp rootcomp.mount()
def enter(self, ev): if not mouseDown: return # mark all rows between initially selected and the one # we are entering clear_selections() row_start = Row(selected_line.closest('tr')).row_num() this_row = Row(self.closest('tr')).row_num() rows = document.get(selector='tr') if this_row > row_start: for num in range(row_start, this_row+1): Row(rows[num]).mark_cells() elif this_row == row_start: Row(rows[row_start]).mark_cells() else: for num in range(this_row, row_start+1): Row(rows[num]).mark_cells()
def extend_selection(self, ev): # mark all cells from selected to ev.target clear_selections() c0, r0 = coords(selected) c1, r1 = coords(ev.target) if c0 > c1: c0, c1 = c1, c0 if r0 > r1: r0, r1 = r1, r0 rows = document.get(selector="tr") for cell in rows[r0].get(selector="td")[c0:c1 + 1]: cell.classList.add("selection-top") for cell in rows[r1].get(selector="td")[c0:c1 + 1]: cell.classList.add("selection-bottom") for row in rows[r0:r1 + 1]: row.childNodes[c0 + 1].classList.add("selection-left") row.childNodes[c1 + 1].classList.add("selection-right")
def enter(self, ev): if not mouseDown: return # mark all rows between initially selected and the one # we are entering clear_selections() row_start = Row(selected_line.closest('tr')).row_num() this_row = Row(self.closest('tr')).row_num() rows = document.get(selector='tr') if this_row > row_start: for num in range(row_start, this_row + 1): Row(rows[num]).mark_cells() elif this_row == row_start: Row(rows[row_start]).mark_cells() else: for num in range(this_row, row_start + 1): Row(rows[num]).mark_cells()
def extend_selection(self, ev): # mark all cells from selected to ev.target clear_selections() c0, r0 = coords(selected) c1, r1 = coords(ev.target) if c0 > c1: c0, c1 = c1, c0 if r0 > r1: r0, r1 = r1, r0 rows = document.get(selector="tr") for cell in rows[r0].get(selector="td")[c0:c1+1]: cell.classList.add("selection-top") for cell in rows[r1].get(selector="td")[c0:c1+1]: cell.classList.add("selection-bottom") for row in rows[r0:r1+1]: row.childNodes[c0+1].classList.add("selection-left") row.childNodes[c1+1].classList.add("selection-right")
def saveNewList(event): val = document['newColumnInput'].value.strip() board_id = document['boardSelect'].value if val: def on_complete(req): response = loads(req.text) if response['success']: loadListsForSelectedBoard() else: alert('Dodanie listy nie powiodło się') req = ajax.ajax() req.bind('complete', on_complete) req.open('POST', '/save_list', True) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send({'name': val, 'board_id': board_id})
def addComment(event): event.preventDefault() content = document['comment_field'].value author = document['body'].__getattribute__('data-username') author_id = document['body'].__getattribute__('data-userid') when = window.Date() if content: appendCommentToDom(author, when, content) data = { 'author': getApiLink('users', author_id), 'content': content, 'task': getApiLink('tasks', task_details['id']) } a2 = ajax.ajax() a2.open('POST', '/api/comments2/?format=json') a2.set_header('content-type', 'application/x-www-form-urlencoded') a2.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) a2.send(data) document['comment_field'].value = ''
def saveTask(event): value = event.target.value lists_id = event.target.__getattribute__('data-lists-id') if value: def task_add_callback(req): if req.status == 201: new_task = loads(req.text) boards_id = new_task['board_list'].split('/')[-2] container = document['tasks_for_list_' + str(boards_id)] appendTask(new_task, container) event.target.value = '' else: alert('Dodanie zadania nie powiodło się') req = ajax.ajax() req.bind('complete', task_add_callback) req.open('POST', '/tasks/?format=json', True) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send({'lists_id': lists_id, 'description': '', 'name': value, 'comments': None})
def saveBoard(name): """ Zwraca ID """ def on_complete(req): response = loads(req.text) if response['success']: document['boardSelect'] <= OPTION(name, value=response['id'], **{'data-background': 1, 'data-star': 'false'}) document['boardNameInput'].style.display = 'none' document['boardSelect'].style.display = '' updateAddBoardButtonState() else: alert(response['message']) req = ajax.ajax() req.bind('complete',on_complete) req.open('POST', '/save_board', True) req.set_header('content-type', 'application/x-www-form-urlencoded') req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value) req.send({'name': name})
def bind_switcher(cls): """ Bind the switch checkbox to functions for switching between types of inputs. """ def show_two_conspect(): cls.is_twoconspect = True # search by class for el in cls.two_conspect_el: el.style.display = "block" cls.whole_conspect_subconspect_el.style.display = "none" def hide_two_conspect(): cls.is_twoconspect = False for el in cls.two_conspect_el: el.style.display = "none" cls.whole_conspect_subconspect_el.style.display = "block" def show_or_hide_two_conspect(ev): val = cls.get() # check / uncheck both checkboxes for el in cls.switcher_els: el.checked = ev.target.checked if ev.target.checked: hide_two_conspect() cls.set(val) return show_two_conspect() cls.set(val) # bind both `conspect_switchers` for el in document.get(selector=".conspect_switcher"): el.bind("change", show_or_hide_two_conspect)
def init_options(): doc["Config"] <= H1("Column visibility") + make_table(headers, 3, True) doc['Config'] <= H1("Items") for base in types: doc["Config"] <= H2(base) + make_table(types[base], 3, item_class=base) doc["Config"] <= H1("Areas") + P( "'Unknown' is npcs that may only exist in the game files and not be present in the game. They are not attached to an area and don't have a BCS spawn script." ) + make_table(areas, 2) for el in doc.get(selector='.save'): if check_storage(el['data-id']): el.checked = False else: el.checked = True @bind('.save', 'change') def save_state(ev): if ev.target.type == 'checkbox': if ev.target.checked: del_storage(ev.target['data-id']) else: set_storage(ev.target['data-id'], 'unchecked')
def refresh(): print('refresh') expo_list = [] document['expo_list'].clear() for item in document.get(name="cbx"): if (item.checked == True): date_info = document['datepicker'].value.split( '-') #0:year,1:month,2:day lines = get_file_text(item.value.lower() + '.json') expo_list += json.loads(lines)[date_info[0]][str(int( date_info[1]))] #show_expo_list(expo_list_year) #expo_list += list(filter(lambda x: (x['start'][:7]==date_info[0]+'/'+date_info[1])or(x['end'][:7]==date_info[0]+'/'+date_info[1]),expo_list_year)) #show_expo_list(expo_list) expo_list.sort(key=lambda x: (int(x['start'][:4]) * 10000 + int(x['start'][ 5:7]) * 100 + int(x['start'][8:10]))) latest_expo = 1 goto_li = '' for expo in expo_list: left_days = check_date(expo) if (left_days == 0): li = gen_li(expo, 'am-text-danger') document['expo_list'] <= li if (goto_li == ''): goto_li = li elif (left_days > 0 and latest_expo == 1): latest_expo = 0 li = gen_li(expo, 'am-text-success') document['expo_list'] <= li if (goto_li == ''): goto_li = li else: document['expo_list'] <= gen_li(expo) print('Hello world!') goto_li.scrollIntoView()
def init_main(): t = doc['Main'] t.text = '' t <= P("This page is updated as you make changes on the Weights and Flags page and only shows non-zero weights and set flags. Changes to weights here are also reflected on those pages.") table = TABLE() th = TR() th <= TH("Damage") th <= TH("Jewel Mod") table <= th for m in mjson[current_version]: if float(doc[m['name']].value): table <= TR(TD(f'<input type="number" data-id="{m["name"]}" value="{doc[m["name"]].value}" step="0.1", class="main_weight">') + TD(m['desc'])) t <= table table = TABLE(TR(TH("Flag Group") + TH("Value"))) flags = {} for elt in doc.get(selector='.flag_val'): temp = elt if temp.checked and temp['data-type'] != 'ignore': if temp['data-type'] not in flags: flags[temp['data-type']] = [] flags[temp['data-type']].append(temp['data-id']) # Special section for charge counts charge_count = [] for elt in [doc['PowerCount'], doc['FrenzyCount'], doc['EnduranceCount'], doc['ImpaleStacks']]: if int(elt.value): name = elt['id'][:-5] if elt['id'] != 'ImpaleStacks' else "Number of Impales on Target" charge_count.append(f"{name} ({elt.value})") if charge_count: flags['Misc Counts'] = charge_count for f in flags: table <= TR(TD(f) + TD(', '.join(flags[f]))) t <= P("Summary of set flags. Make changes on Flags page.") + table @bind('.main_weight', 'change') def update_weight(ev): tmp = ev.target doc[tmp['data-id']].value = tmp.value
def gameover(): global game document.get(selector="h1")[0].text= "Game Over"
def canvas(self): return document.get(selector='canvas')[0]
def clear_selections(): for klass in "column-select", "selected", "row-select": for cell in document.get(selector="." + klass): cell.classList.remove(klass)
def callback(response): r = loads(response.text) if r['success']: document.get(name='registerBtn')[0].disabled = False else: document.get(name='registerBtn')[0].disabled = True