def charger_ouvrage(rq): prp = json.loads(rq.text) sel_auteur = SELECT(name='auteur', id='auteur') sel_auteur <= (OPTION('{titre} {prenom} {particule} {nom}'.format( **auteur).replace("' ", "'"), value=auteur['id'], selected=(auteur['id'] == prp['auteur']['id'])) for auteur in json.loads(requete('/db/liste/auteurs'))) sel_editeur = SELECT(name='editeur', id='editeur') sel_editeur <= (OPTION(editeur['nom'], value=editeur['id'], selected=(editeur['id'] == prp['editeur']['id'])) for editeur in json.loads(requete('/db/liste/editeurs'))) bouton = BUTTON('Modifier') bouton.bind('click', lambda ev: enregistrer(ev, 'ouvrage')) return ( INPUT(type='hidden', value=str(prp['id']), id='id') + tableau([ [ 'Titre', INPUT( type='text', name='titre', value=prp['titre'], id='titre') ], ['Auteur', sel_auteur], ['Éditeur', sel_editeur], ], entete=False, trier=False) + bouton)
def create_search(self): dindex.style.display = 'none' dtop.clear() doutput.clear() # document.title = f'{self.release} Search' dtop <= SPAN(f'{self.release}') dtop <= SPAN(A('Index', href='#')) # dsearch = DIV() doutput <= dsearch dsearch.style.paddingLeft = '20px' chars = sorted({item[0].upper() for item in self.udf_list}) div = DIV() div.style.marginBottom = '10px' dsearch <= div for c in chars: span = SPAN(c) span.style.color = 'blue' span.style.textDecoration = 'underline' span.style.padding = '2px 5px 10px 5px' span.style.cursor = 'pointer' span.onclick = self.click_one div <= span # input = INPUT(type="text") input.title = 'Search' input.style.width = '40ch' input.style.marginBottom = '10px' dsearch <= input input.bind('input', self.input_change) # dsearch <= DIV(id='searchresult')
class BuscaAlimento(DIV): sel = None nutTab = None inText = None def __init__(self): DIV.__init__(self) #, style={'max-width':'90px'}) selTable = TABLE() self <= selTable self.inText = INPUT(Class="form-control") self.inText.bind('keyup', self.entrou) selTable <= TR(TD(P("Busca: ") + self.inText)) #,name="intext")) self.sel = SELECT(size=8, Class='form-control') # style={'max_width':'90px'}) self.sel.bind('input', self.selec) selTable <= TR(TD(self.sel)) self.sel.style.display = 'none' self.nutTab = MostraNut() self <= self.nutTab def entrou(self, event): if event.which == 13: req = ajax.ajax() req.bind('complete', self.complete) req.open('POST', '/nutsvc', True) req.set_header('content-type', 'application/x-www-form-urlencoded') d = {'op': 'QUERY', 'q': event.currentTarget.value} req.send(d) def complete(self, r): if r.status == 200 or r.status == 0: result = json.loads(r.text) if len(result) == 0: alert("Nenhum alimento encontrado") self.sel.style.display = 'none' return self.sel.clear() for l in result: self.sel.style.display = 'block' self.sel.style.width = '90pw' self.sel <= OPTION(l[1], value=l[0]) def selec(self, event): self.sel.style.display = 'none' #alert(dir(event.currentTarget)) #alert(event.currentTarget.options[event.currentTarget.selectedIndex].text) #alert(event.currentTarget.text[event.currentTarget.selectionRange]) #alert(dir(self.inText)) #self.inText.set_text(event.currentTarget.options[event.currentTarget.selectedIndex].text) self.inText.value = event.currentTarget.options[ event.currentTarget.selectedIndex].text medida = EscolheMedida(event.currentTarget.value, self.selected) self <= medida medida.showModal() def selected(self): alert("selected")
def login_form(): form = FORM(id="meu-forme", action="#", method="GET", target="_blank") form <= LABEL('seu nome', For='nome', name="nome") form <= INPUT(id='nome') form <= BR() form <= LABEL('sua senha', For='senha', senha="senha") form <= INPUT(id='senha', type='password', required=True) form <= BR() form <= INPUT(id='submit', type='submit') return form
def init_flags(): data = [('useFrenzyCharges', 'Frenzy'), ('usePowerCharges', 'Power'), ('useEnduranceCharges', 'Endurance')] t = make_table(data, 3, 'Charges') doc['Flags'] <= STRONG('Charges:') + ' Do you sustain charges?' + t + BR() t = TABLE() t <= TR(TD(INPUT(type="number", Id="PowerCount", value="0", data_normal="1", style={"width": "3em"}, Class="dps_val")) + TD('Power')) t <= TR(TD(INPUT(type="number", Id="FrenzyCount", value="0", data_normal="1", style={"width": "3em"}, Class="dps_val")) + TD('Frenzy')) t <= TR(TD(INPUT(type="number", Id="EnduranceCount", value="0", data_normal="1", style={"width": "3em"}, Class="dps_val")) + TD('Endurance')) t <= TR(TD(INPUT(type="number", Id="ImpaleStacks", value="0", data_normal="1", style={"width": "3em"}, Class="dps_val")) + TD('Number of Impales on Target')) doc['Flags'] <= STRONG('Misc Counts:') + ' The "count" of various things affecting your build.' + t + BR() data = ['Attack', 'Spell'] t = make_table(data, 2, 'Type') doc['Flags'] <= STRONG('Type:') + ' Generally select 1 based on your combat style' + t + BR() data = ['Mace', 'Bow', 'Wand', 'Claw', 'Staff', 'Sword', 'Axe', 'Dagger', 'Trap', 'Mine', 'Totem'] t = make_table(data, 4, 'Class') doc['Flags'] <= STRONG('Class:') + ' Select your weilded weapon types. Trap/Mine/Totem if you are using those supports' + t + BR() data = ['Elemental', 'Fire', 'Cold', 'Lightning', 'Projectile', 'Melee', 'Area', 'Spectre', 'Exerted', 'Trigger', 'Vaal'] t = make_table(data, 4, 'Tags') doc['Flags'] <= STRONG('Tags:') + ' Check all the tags that match your primary skill' + t + BR() data = ['Shield', ('DualWielding', 'Dual Wielding'), ('TwoHandedWeapon', 'Two Handed Weapon')] t = make_table(data, 3, 'Hands') doc['Flags'] <= STRONG('Hands:') + ' Choose 1 based on wielded weapons' + t + BR() data = [('KilledRecently', 'You Kill'), ('MinionsKilledRecently', 'Minion Kill'), ('NoRecentKill', 'Not Kill'), ('CritRecently', 'Crit'), ('NoRecentCrit', 'Not Crit'), ('UsedMinionSkillRecently', 'Minion Skill'), 'Stun', 'Shatter', ('beShocked', 'Be Shocked')] t = make_table(data, 3, 'Recently') doc['Flags'] <= STRONG('Recently:') + " Tic all the things your build can do 'recently'" + t + BR() data = [('EnemyPoisoned', 'Poisoned'), ('EnemyBlinded', 'Blinded'), ('EnemyIgnited', 'Ignited'), ('EnemyBurning', 'Burning'), ('EnemyChilled', 'Chilled'), ('EnemyFrozen', 'Frozen'), ('EnemyShocked', 'Shocked'), ('EnemyMaimed', 'Maimed')] t = make_table(data, 4, 'Enemy is') doc['Flags'] <= STRONG('Enemy is:') + ' Status effects on your target' + t + BR() data = ['Spellslinger', ('SpellslingerDW', 'Spellslinger(DW)'), 'BattleMage', ('Leeching', 'Leeching (Generic)'), ('leechLife', 'Leeching Life'), ('leechMana', 'Leeching Mana'), ('UsingFlask', 'Flasked'), ] t = make_table(data, 3, 'You are/have') doc['Flags'] <= STRONG('You are/have:') + ' Tic all the things affecting you' + t + P(STRONG('Spellslinger/Battlemage Notes:') + " Only select, at max, one of the Spellslingers and remember Spellslinger only works with wands. Physical damage is not correct as it depends on base item, quality, %ipd. Existing search mods don't allow for a meaningful weight to be generated.") + BR() data = [('NearbyRareUnique', 'Nearby Rare or Unique Monster'), ('NearbyEnemy', 'Nearby Enemy (helm mods)'), ('otherringshaper', 'Other Ring is Shaper'), ('otherringelder', 'Other Ring is Elder')] t = make_table(data, 1, 'Other Options') doc['Flags'] <= STRONG('Other options:') + ' choices that don\'t neatly fit a section' + BR() + t
def charger_editeur(rq): prp = json.loads(rq.text) bouton = BUTTON('Modifier') bouton.bind('click', lambda ev: enregistrer(ev, 'editeur')) return (INPUT(type='hidden', value=str(prp['id']), id='id') + tableau([ [ 'Nom', INPUT(type='text', name='nom', id='nom', value=prp['nom']) ], ], entete=False, trier=False) + bouton)
def cabecalho(): div = DIV(Class="cabecalho") logo = DIV(Class="logo-cabecalho") logo <= A("Meu Blog", href="index.html") pesquisa = DIV(Class="pesquisa") pesquisa <= INPUT(type="text") pesquisa <= INPUT(type="submit", value="Pesquisar") div <= logo div <= pesquisa return div
def make_table(data, w, section): t = TABLE() tr = TR() for c, d in enumerate(data, 1): if isinstance(d, str): tr <= TD(LABEL(INPUT(type='checkbox', Id=d, Class='flag_val', data_id=d, data_type=section) + d)) else: tr <= TD(LABEL(INPUT(type='checkbox', Id=d[0], Class='flag_val', data_id=d[1], data_type=section) + d[1])) if not c % w: t <= tr tr = TR() if c % w: t <= tr return t
def __init__(self): DIV.__init__(self) #, style={'max-width':'90px'}) selTable = TABLE() self <= selTable self.inText = INPUT(Class="form-control") self.inText.bind('keyup', self.entrou) selTable <= TR(TD(P("Busca: ") + self.inText)) #,name="intext")) self.sel = SELECT(size=8, Class='form-control') # style={'max_width':'90px'}) self.sel.bind('input', self.selec) selTable <= TR(TD(self.sel)) self.sel.style.display = 'none' self.nutTab = MostraNut() self <= self.nutTab
class BuscaAlimento(DIV): sel=None nutTab=None inText=None def __init__(self): DIV.__init__(self) #, style={'max-width':'90px'}) selTable = TABLE() self <= selTable self.inText = INPUT(Class="form-control") self.inText.bind('keyup',self.entrou) selTable<=TR(TD(P("Busca: ")+self.inText)) #,name="intext")) self.sel = SELECT(size=8,Class='form-control') # style={'max_width':'90px'}) self.sel.bind('input',self.selec) selTable<=TR(TD(self.sel)) self.sel.style.display = 'none' self.nutTab = MostraNut() self <= self.nutTab def entrou(self, event): if event.which==13: req = ajax.ajax() req.bind('complete',self.complete) req.open('POST','/nutsvc', True) req.set_header('content-type','application/x-www-form-urlencoded') d = {'op':'QUERY','q':event.currentTarget.value} req.send(d) def complete(self,r): if r.status==200 or r.status==0: result = json.loads(r.text) if len(result)==0: alert("Nenhum alimento encontrado") self.sel.style.display = 'none' return self.sel.clear() for l in result: self.sel.style.display = 'block' self.sel.style.width='90pw' self.sel<=OPTION(l[1], value=l[0]) def selec(self, event): self.sel.style.display = 'none' #alert(dir(event.currentTarget)) #alert(event.currentTarget.options[event.currentTarget.selectedIndex].text) #alert(event.currentTarget.text[event.currentTarget.selectionRange]) #alert(dir(self.inText)) #self.inText.set_text(event.currentTarget.options[event.currentTarget.selectedIndex].text) self.inText.value = event.currentTarget.options[event.currentTarget.selectedIndex].text medida = EscolheMedida(event.currentTarget.value, self.selected) self<=medida medida.showModal() def selected(self): alert("selected")
def init_show_hide(): # initialize options element = set() weapon = set() for char in characters: if char == 'traveler': continue element.add(characters[char]['element']) weapon.add(characters[char]['weapon']) # selected cst = SELECT(Id=f"selected", Class=f"save onehundred") for s in ['any', 'checked', 'unchecked']: cst <= OPTION(s.capitalize(), value=s) # element est = SELECT(Id=f"element", Class=f"save onehundred") for s in ['any'] + sorted(element): est <= OPTION(s.capitalize(), value=s) # weapon wst = SELECT(Id=f"weapon", Class=f"save onehundred") for s in ['any'] + sorted(weapon): wst <= OPTION(s.capitalize(), value=s) t = TABLE(TR(TH() + TH('Option'))) t <= TR(TD('Character', Class="right_text") + TD(cst)) t <= TR(TD('Element', Class="right_text") + TD(est)) t <= TR(TD('Weapon', Class="right_text") + TD(wst)) t <= TR(TD('Character Search', Class="right_text") + TD(INPUT(Type='text', Id="keywords") + BUTTON('x', Id='clear_keywords'))) doc['show_hide'] <= t + P("Note that all selections have to be true for a character to be visible. Additionally the keyword search overrides all other filter settings so clear it to use them.")
def __init__(self, idAli, cb): DIALOG.__init__(self) tab = TABLE() self <= tab self.callback = cb #self.inText = INPUT(Class="form-control") #self.inText.bind('keyup',self.entrou) #tab<=TR(TD('Peso (g):')+TD(self.inText)) self.sel = SELECT(Class='form-control', size=8) # style={'max_width':'90px'}) ##self.sel.bind('input',self.selected) #tab<=TH("Escolha medida", colspan=2) self.inMedQty = INPUT(Class="form-control", size=4) tab <= TR(TD('Medida caseira, quantidade') + TD(self.inMedQty)) tab <= TR(TD(self.sel, colspan=2)) add = SPAN(Class='glyphicon glyphicon-ok-circle') add.bind('click', self.added) can = SPAN(Class='glyphicon glyphicon-remove-circle') can.bind('click', self.cancelled) tab <= TR( TD(can, style={ 'text-align': 'right', 'padding': '6pw' }) + TD(add, style={ 'text-align': 'center', 'padding': '6pw' })) req = ajax.ajax() req.bind('complete', self.complete) req.open('POST', '/nutsvc', True) req.set_header('content-type', 'application/x-www-form-urlencoded') d = {'op': 'MEDIDAS', 'q': idAli} req.send(d)
def login_form(): form = FORM(Class='form login-form', id="meu-forme", action="#", method="GET", target="blank") form <= H2('Meu formulário') form <= LABEL('seu nome', For='nome') form <= INPUT(id='nome', name='nome', required=True) form <= BR() form <= LABEL('sua senha', For='senha') form <= INPUT(id='senha', type='password', name='senha', required=True) form <= BR() form <= INPUT(id='submit', type='submit') document <= form
def __init__(self): DIV.__init__(self) #, style={'max-width':'90px'}) selTable = TABLE() self <= selTable self.inText = INPUT(Class="form-control") self.inText.bind('keyup',self.entrou) selTable<=TR(TD(P("Busca: ")+self.inText)) #,name="intext")) self.sel = SELECT(size=8,Class='form-control') # style={'max_width':'90px'}) self.sel.bind('input',self.selec) selTable<=TR(TD(self.sel)) self.sel.style.display = 'none' self.nutTab = MostraNut() self <= self.nutTab
def render(self): txt = TxtManager() todo = List() app = group( DIV(Class="container d-flex flex-column justify-content-center"), group(DIV(Class="container-sm m-3"), [ DIV(style={"margin": "10px"}), txt.render(), H1("Todo List With Breact"), DIV(style={"margin": "10px"}), todo.render(), group(DIV(Class="row"), [ group(DIV(Class="col-sm form-group"), [ LABEL("Enter Title", to="inputt", Class="form-label"), title := INPUT( id="inputt", type="text", Class="form-control"), ]), description := group(DIV(Class="col-sm form-group"), [ LABEL("Enter Description", to="inputts", Class="form-label"), TEXTAREA( id="inputts", type="text", Class="form-control") ]), ]), btn := BUTTON("Submit please", Class="btn btn-primary m-2"), DIV(style={"margin": "40px"}) ])) @bind(title, "keyup") def updateTitle(e): txt.setState({"title": e.target.value}) @bind(description, "keyup") def updateDesc(e): txt.setState({"description": e.target.value}) @bind(btn, "click") def submit(e): submission = { "title": txt.state["title"], "description": txt.state["description"] } todo.state["items"].append(submission) todo.setState({"items": todo.state["items"]}) return app # document["root"] <= Main().render()
def _create_input( name, type, label='', Class='', text='', value='', required=False, ): """ Cria um input completo. Baseados nas implementações do CSS, insere uma div `form-group` um input e um label Args: ---- name: id do input type: tipo do input label: texto do label Class: classe CSS text: texto do componente value: valur do componente required: input validator required Retorna uma div do grupo com o elemto inserido na div. Example: ------- >>> _create_input('nome', 'text', 'Seu nome') <div class="form-group"> <label for="nome"> Seu nome </label> <input id="nome", type="text"> </div> """ d = DIV(Class='form-group') d <= LABEL(f'{label}: ' if label else '', For=name, id=f'l{name}') d <= INPUT( text, id=name, name=name, type=type, Class=Class, value=value, required=required, ) return d
def formulaire(obj, donnees): bouton = BUTTON('Filtrer') bouton.bind( 'click', lambda ev: charger_liste( ev, obj, actualiser=True, criteres={donnee[1]: doc[donnee[1]].value for donnee in donnees})) return ( tableau([[donnee[0], INPUT(type='text', name=donnee[1], id=donnee[1])] for donnee in donnees], entete=False, trier=False) + bouton)
def make_table(m_data, w, header=False, item_class=''): t = TABLE() tr = TR() for c, d in enumerate(m_data, 1): if isinstance(d, str): new_id = f"{item_class + '_' if item_class else ''}{d}" for a, b in [(' ', '_'), ('\'', '_'), ('+', '_')]: new_id = new_id.replace(a, b) tr <= TD( LABEL( INPUT( type='checkbox', Id=new_id, Class=f'save {"header" if header else "flag_val"}', data_id=f"{item_class + '_' if item_class else ''}{d}") + d)) if not c % w: t <= tr tr = TR() if c % w: t <= tr return t
def cadastro_pessoa(): form = FORM(id="meu-form", action="#", method="get", target="_blank") form <= LABEL('Nome', id='nome') form <= INPUT(id='Nome', name='Nome') form <= BR() form <= LABEL('CPF', id='cPF') form <= INPUT(id='CPF', type='password', name='CPF') form <= BR() form <= LABEL('Telefone', id='telefone') form <= INPUT(id='Telefone', type='password', name='Telefone') form <= BR() form <= LABEL('Adicionar', id='add') form <= BUTTON(id='submit', name='submit', type='button') form <= BR() form <= LABEL('Mostrar lista de pessoas:', id='stud_list') form <= BUTTON(id='all_students', name='students list', type='button') form <= BR() form <= H1('Deletar pessoa do banco de dados') form <= LABEL('ID da pessoa', id='delete_stud') form <= INPUT(id='id', name='ID') form <= BR() form <= LABEL('Deletar: ', id='delete_stud') form <= BUTTON(id='delete', name='delete', type='button') form <= H1('Adicionar curso a pessoa') form <= LABEL('ID da pessoa', id='id_pessoa') form <= INPUT(id='id_pcurso', name='ID') form <= BR() form <= LABEL('Curso', id='curso_type') form <= INPUT(id='curso', name='Curso') form <= BR() form <= LABEL('Adicionar curso: ', id='add_pessoa_curso') form <= BUTTON(id='add_pc', name='add_pc', type='button') form <= BR() form <= LABEL('Mostrar cursos: ', id='cursos') form <= BUTTON(id='show_curso', name='show_cursos', type='button') #open('GET', 'http://127.0.0.1:5000/alunos/add', True) #get('http://127.0.0.1:5000/alunos/add') return form
"""welcome page with two buttons login and register""" div1 = DIV(id="welcome") button1 = BUTTON("Register", id="but_register") button2 = BUTTON("Login", id="but_login") div1 <= button1 + button2 container <= div1 """event button for show login div and show register div """ doc['but_login'].bind('click', login) doc['but_register'].bind('click', register) """login page"""" div2 = DIV(id="login", Class="w3-center") title1 = H1("Login in") input1 = INPUT(placeholder="Your email") input2 = INPUT(placeholder="Your password") back_button = BUTTON("Back", id="back_login") button_submit = BUTTON("Submit") div2 <= title1 + input1 + input2 + BR() + \ back_button + BR() + button_submit container <= div2 doc['back_login'].bind('click', back) """register page""" div3 = DIV(id="register", Class="w3-center") title2 = H1("Register") input3 = INPUT(placeholder="Your email") input4 = INPUT(placeholder="Your password") back_button = BUTTON("Back", id="back_register") button_submit = BUTTON("Submit")
def on_complete(req): response = loads(req.text) if response['success']: for l in response['lists']: column = DIV() column.class_name = 'large-3 columns listsColumns' tasks_container = DIV(id='tasks_for_list_' + str(l['id']), data_list_id=l['id']) tasks_container.class_name = 'tasksContainer' column <= tasks_container header = H4(l['name']) archive_icon = SPAN() archive_icon.class_name = 'fi-trash size-24 archive_list_icon' archive_icon.bind('click', archiveList) header <= archive_icon tasks_container <= header new_task_input_params = {'placeholder': 'Nowe zadanie', 'class': 'newTaskInput', 'type': 'text', 'data-lists-id': l['id']} new_task_input = INPUT(**new_task_input_params) tasks_container <= new_task_input def drag_over(ev): ev.dataTransfer.dropEffect = 'move' ev.preventDefault() 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)}) tasks_container.bind('dragover', drag_over) tasks_container.bind('drop', on_drop) def addColours(task, task_div): colour_container = DIV() colour_container.class_name = 'colour_container' task_div.append(colour_container) colours = task.get('colours', []) for colour_nr in colours: colour_div = DIV() colour_div.class_name = 'label-colour' + colour_nr colour_container.append(colour_div) def appendTask(task, container): task_div_params = {'class': 'taskDiv', 'data-task-id': task['id'], 'id': 'task_' + str(task['id']), 'draggable': True} task_div = DIV(**task_div_params) task_name = H3(task['name'], **{'data-task-id': task['id']}) task_name.class_name = 'task_name_header' addColours(task, task_div) task_div <= task_name container <= task_div def drag_start(ev): ev.dataTransfer.setData('text', ev.target.id) ev.dataTransfer.effectAllowed = 'move' task_div.bind('dragstart', drag_start) def taskDetails(event): #Uwaga na niedziedziczone atrybuty przy dziedziczonych eventach! task_id = event.target.__getattribute__('data-task-id') def taskDetailsLoaded(req): task_details = loads(req.text) def usersLoaded(req): users = loads(req.text) container = DIV() container <= H2('Edycja zadania') form = FORM(method='PATCH', action='#') input0 = INPUT(name='id', type='hidden', value=task_details['id'], id='id_field') form <= input0 row1 = DIV() row1.class_name = 'row' cell11 = DIV() cell11.class_name = 'large-6 columns' label11 = LABEL('Nazwa') input11 = INPUT(placeholder='Nazwa zadania', type='text', value=task_details['name'], name='name', id='name_field') label11 <= input11 cell11 <= label11 error_panel1 = DIV(id='name_error') error_panel1.class_name = 'panel error' cell11 <= error_panel1 row1 <= cell11 row2 = DIV() row2.class_name = 'row' cell2 = DIV() cell2.class_name = 'large-6 columns' label2 = LABEL('Opis') input2 = INPUT(placeholder='Opis zadania', name='description', id='description_field', type='text') input2.value = task_details['description'] label2 <= input2 cell2 <= label2 row2 <= cell2 cell3 = DIV() cell3.class_name = 'large-6 columns' label3 = LABEL('Przypisane do') input3 = SELECT(name='assignee', id='assignee_field') input3 <= OPTION('---', value=None) for user in users: input3 <= OPTION(user['username'], value=getApiLink('users', user['id'])) input3.value = task_details['assignee'] label3 <= input3 cell3 <= label3 row1 <= cell3 cell7 = DIV() cell7.class_name = 'large-6 columns' label7 = LABEL('Termin wykonania') input7 = INPUT(name='deadline', id='deadline_field', placeholder='yyyy-mm-dd', type='text') input7.value = task_details['deadline'] if task_details['deadline'] else '' label7 <= input7 cell7 <= label7 error_panel7 = DIV(id='deadline_error') error_panel7.class_name = 'panel error' cell7 <= error_panel7 row2 <= cell7 row3 = DIV() row3.class_name = 'row' cell33 = DIV() cell33.class_name = 'large-6 columns' label33 = LABEL('Trudność') input33 = SELECT(name='difficulty', id='difficulty_field') input33 <= OPTION('---', value='None') input33 <= OPTION('łatwe', value='easy') input33 <= OPTION('średnie', value='intermediate') input33 <= OPTION('trudne', value='hard') if task_details['difficulty'] and task_details['difficulty'] in ('easy', 'intermediate', 'hard'): input33.value = task_details['difficulty'] label33 <= input33 cell33 <= label33 cell34 = DIV() cell34.class_name = 'large-6 columns' label34 = LABEL('') label34 <= BR() input34 = BUTTON('Archiwizuj', id='archive_task', data_task_id=task_details['id']) input34.class_name = 'button tiny' label34 <= input34 cell34 <= label34 row3 <= cell33 row3 <= cell34 input34.bind('click', archiveTask) row6 = DIV() row6.class_name = 'row' cell6 = DIV() cell6.class_name = 'large-12 columns' cell6.id = 'comments-container' cell6 <= H4('Komentarze') def appendCommentToDom(author, when, content): length = len(cell6.get(selector='.comment')) colour = '' if length % 2 == 0 else ' callout' #colour = '' panel = DIV() panel.class_name = 'panel comment' + colour panel <= B('{0} dnia {1}'.format(author, when)) panel <= P(content) cell6 <= panel if len(task_details['comments']) == 0: panel = DIV() panel.class_name = 'panel' panel <= P('No comments') cell6 <= panel else: i = 0 for comment in task_details['comments']: author = [user['username'] for user in users if getApiLink('users', user['id']) == comment['author']].pop() when = comment['created_at'] content = comment['content'] appendCommentToDom(author, when, content) row6 <= cell6 row5 = DIV() row5.class_name = 'row' cell5 = DIV() cell5.class_name = 'large-12 columns' label5 = LABEL('Skomentuj') input5 = TEXTAREA(placeholder='Treść komentarza', name='comment', id='comment_field') label5 <= input5 cell5 <= label5 comment_btn = A('Dodaj komentarz', href='#') comment_btn.class_name = 'button tiny' cell5 <= comment_btn row5 <= cell5 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 = '' comment_btn.bind('click', addComment) row4 = DIV() row4.class_name = 'row' cell4 = DIV() cell4.class_name = 'large-12 columns' submit_btn = A('Zapisz zmiany', type='submit', href='#') submit_btn.class_name = 'button tiny' cell4 <= submit_btn row4 <= cell4 form <= row1 form <= row2 form <= row3 form <= row4 form <= row6 form <= row5 container <= form for i in range(1, 6): colour_name = 'colour{0}'.format(i) if str(i) in task_details['colours']: document[colour_name].class_name = 'colour-btn checked' else: document[colour_name].class_name = 'colour-btn' #/api/tasks/ 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 submit_btn.bind('click', on_submit) show_modal(container) req = ajax.ajax() req.open('GET', '/api/users/?format=json', True) req.bind('complete', usersLoaded) req.send() req = ajax.ajax() req.open('GET', '/api/tasks/' + task_id + '/?format=json', True) req.bind('complete', taskDetailsLoaded) req.send() task_div.bind('click', taskDetails) l['tasks'].sort(key=itemgetter('order_in_list', 'id')) for task in l['tasks']: appendTask(task, tasks_container) document['listContainer'] <= column 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}) new_task_input.bind('blur', saveTask) column = DIV() column.class_name = 'large-3 columns listsColumns' new_input = INPUT(id='newColumnInput', placeholder='Nowa lista', type='text') column <= new_input document['listContainer'] <= column new_input.bind('blur', saveNewList) #console.log(document.get(selector='.newTaskInput')[0].focus()) else: alert('Pobranie list nie powiodło się')
def init_inventory(): # Create a table of items we might need and store their ids in a lookup table # char xp, weapon xp, and mora t_own = TABLE(Class='borders center') t_own <= TR(TH(strings["item"]) + TH(strings["need"]) + TH(strings["have"]) + TH(strings["missing_"])) t_own <= TR(TD(IMG(src=f"img/wep_xp.png", alt=strings['wep_xp'], title=strings['wep_xp'], loading="lazy")) + TD('0', Id='wep_xp-total') + TD(INPUT(Type='number', min='0', step="1", value='0', Id='wep_xp-user', Class='save')) + TD('0', Id='wep_xp-need', Class='good')) t_own <= TR(TD(IMG(src=f"img/wep_xp_sub_1.png", alt=strings['wep_xp'], title=strings['wep_xp'], loading="lazy")) + TD() + TD(INPUT(Type='number', min='0', step="1", value='0', Id='wep_xp_sub_1-user', Class='save')) + TD()) t_own <= TR(TD(IMG(src=f"img/wep_xp_sub_0.png", alt=strings['wep_xp'], title=strings['wep_xp'], loading="lazy")) + TD() + TD(INPUT(Type='number', min='0', step="1", value='0', Id='wep_xp_sub_0-user', Class='save')) + TD()) t_own <= TR(TD(IMG(src=f"img/mora.png", alt=strings['mora'], title=strings['mora'], loading="lazy")) + TD('0', Id='mora-total') + TD(INPUT(Type='number', min='0', step="1", value='0', Id='mora-user', Class='save')) + TD('0', Id='mora-need', Class='good')) t_own <= TR(TD(IMG(src=f"img/xp.png", alt=strings['xp'], title=strings['xp'], loading="lazy")) + TD('0', Id='xp-total') + TD(INPUT(Type='number', min='0', step="1", value='0', Id='xp-user', Class='save')) + TD('0', Id='xp-need', Class='good')) t_own <= TR(TD(IMG(src=f"img/xp_sub_1.png", alt=strings['xp'], title=strings['xp'], loading="lazy")) + TD() + TD(INPUT(Type='number', min='0', step="1", value='0', Id='xp_sub_1-user', Class='save')) + TD()) t_own <= TR(TD(IMG(src=f"img/xp_sub_0.png", alt=strings['xp'], title=strings['xp'], loading="lazy")) + TD() + TD(INPUT(Type='number', min='0', step="1", value='0', Id='xp_sub_0-user', Class='save')) + TD()) doc['inventory'] <= P(strings['convert_notice']) + t_own width = 3 alt_width = 2 row = 0 prev_section = "init" t_own = TABLE(Class='borders center spacer') t_head = TR() for c in range(width): t_head <= TH(strings["item"]) + TH(strings["need"]) + TH(strings["have"]) + TH(strings["missing_"]) if c < width - 1: t_head <= TH(Class="spacer") c = 0 t_own <= t_head t_row = TR(Class='tr_odd') lookup = {0: 14, 1: 9, 2: 4, 3: 0} for section, item in ingame_order: if section != prev_section: if c % width: if lookup[c]: t_row <= TD(colspan=lookup[c], Class='notvis') t_own <= t_row t_row = TR(Class='tr_odd' if row % 2 else 'tr_even') row += 1 c = 0 if prev_section != 'init': c = 0 t_own <= TR(TD(colspan=14), Class='empty_row') prev_section = section if section in ['element_1', 'common', 'common_rare', 'wam', 'talent']: if section in ['element_1', 'wam']: if c: if lookup[c]: t_row <= TD(colspan=lookup[c], Class='notvis') t_own <= t_row t_row = TR(Class='tr_odd' if row % 2 else 'tr_even') row += 1 c = 0 t_width = alt_width else: t_width = width prev_section = 'end section' for i in range(len(strings[item])-1, -1, -1): t_td = TD(IMG(src=f"img/{item}_{i}.png", alt=strings[item][i], title=strings[item][i], loading="lazy")) + TD('0', Id=f"{item}_{i}-total") + TD(INPUT(Type='number', min='0', step="1", value='0', Id=f"{item}_{i}-user", Class='save')) + TD('0', Id=f"{item}_{i}-need") c += 1 t_row <= t_td if not (c % t_width): if lookup[c]: t_row <= TD(colspan=lookup[c] if t_width == 3 else lookup[c] + 1, Class='notvis') t_own <= t_row t_row = TR(Class='tr_odd' if row % 2 else 'tr_even') c = 0 row += 1 elif c % width < width: t_row <= TD() else: # section in ['boss', 'element_2', 'local', 'special']: t_td = TD(IMG(src=f"img/{item}.png", alt=strings[item], title=strings[item], loading="lazy")) + TD('0', Id=f"{item}-total") + TD(INPUT(Type='number', min='0', step="1", value='0', Id=f"{item}-user", Class='save')) + TD('0', Id=f"{item}-need") c += 1 t_row <= t_td if not (c % width): if lookup[c]: t_row <= TD(colspan=lookup[c], Class='notvis') t_own <= t_row t_row = TR(Class='tr_odd' if row % 2 else 'tr_even') row += 1 c = 0 elif c % width < width: t_row <= TD() if c % width: if lookup[c]: t_row <= TD(colspan=lookup[c], Class='notvis') t_own <= t_row doc['inventory'] <= t_own b_reset = BUTTON(strings["reset_all_data"], Id='reset_all') doc["reset"] <= b_reset b_reset = BUTTON(strings["reset_character"], Id='reset_character') doc["reset"] <= b_reset b_reset = BUTTON(strings["reset_inventory"], Id='reset_inventory') doc["reset"] <= b_reset
def init_characters(): t = TABLE(Class='body') t <= COLGROUP( COL() + COL() + COL(Class='left_border') + COL(Class='left_dotted') + COL(Class='left_border') + COL(Class='left_dotted') + COL(Class='left_border') + COL(Class='left_dotted') + COL(Class='left_border') + COL(Class='left_dotted') + COL(Class='left_border') + COL(Class='left_dotted') + COL(Class='left_dotted') + COL(Class='left_border') + COL(Class='left_dotted') + COL(Class='left_dotted') ) t <= TR( TH(strings["character"], colspan=2) + TH(strings["level"], colspan=2) + TH(strings["normal"], colspan=2) + TH(strings["skill"], colspan=2) + TH(strings["burst"], colspan=2) + TH(strings["weapon"], colspan=3) + TH(strings["artifacts"], colspan=3) ) t <= TR( TH() + TH(strings["name"]) + TH(strings["now"]) + TH(strings["goal"]) + TH(strings["now"]) + TH(strings["goal"]) + TH(strings["now"]) + TH(strings["goal"]) + TH(strings["now"]) + TH(strings["goal"]) + TH() + TH(strings["now"]) + TH(strings["goal"]) + TH(strings["click_to_remove"], colspan=3) ) for char in sorted(characters): if char == 'traveler': continue # set up level select lvlc = SELECT(Id=f"level_c-{char}", Class=f"{char} save") lvlt = SELECT(Id=f"level_t-{char}", Class=f"{char} save") for lvl in [lvlc, lvlt]: for c, val in [(0, "1"), (1, "20"), (11, "20 A"), (2, "40"), (12, "40 A"), (3, "50"), (13, "50 A"), (4, "60"), (14, "60 A"), (5, "70"), (15, "70 A"), (6, "80"), (16, "80 A"), (7, "90")]: lvl <= OPTION(f"{val}", value=c) # Set up talent select t1c = SELECT(Id=f"talent_1_c-{char}", Class=f"{char} save") t1t = SELECT(Id=f"talent_1_t-{char}", Class=f"{char} save") t2c = SELECT(Id=f"talent_2_c-{char}", Class=f"{char} save") t2t = SELECT(Id=f"talent_2_t-{char}", Class=f"{char} save") t3c = SELECT(Id=f"talent_3_c-{char}", Class=f"{char} save") t3t = SELECT(Id=f"talent_3_t-{char}", Class=f"{char} save") for st in [t1t, t1c, t2t, t2c, t3t, t3c]: for cost in costs['talent']: st <= OPTION(cost) # Set up weapon select ws = SELECT(Id=f"weapon-{char}", data_id=f"select-{char}", Class=f'weapon {char} save') ws <= OPTION('--', value='--') sort_dict_wep = {} for item in weapons[characters[char]['weapon']]: if weapons[characters[char]['weapon']][item]['wam'] != 'unk': sort_dict_wep[strings[item]] = item else: if f"missing-{item}" not in doc: doc['missing'] <= LI(strings[item], Id=f"missing-{item}") for k in sorted(sort_dict_wep): ws <= OPTION(k, value=sort_dict_wep[k]) wlvlc = SELECT(Id=f"weapon_c-{char}", Class=f"{char} save") wlvlt = SELECT(Id=f"weapon_t-{char}", Class=f"{char} save") for lvl in [wlvlc, wlvlt]: for c, val in [(0, "1"), (1, "20"), (11, "20 A"), (2, "40"), (12, "40 A"), (3, "50"), (13, "50 A"), (4, "60"), (14, "60 A"), (5, "70"), (15, "70 A"), (6, "80"), (16, "80 A"), (7, "90")]: lvl <= OPTION(f"{val}", value=c) # Create table row for character t <= TR( TD(INPUT(Id=f"check-{char}", type='checkbox', data_id=f"check-{char}", Class='char_select save')) + TD(IMG(src=f"img/{char}.png", alt=strings[char], title=strings[char], loading="lazy")) + TD(lvlc) + TD(lvlt) + TD(t1c) + TD(t1t) + TD(t2c) + TD(t2t) + TD(t3c) + TD(t3t) + TD(ws) + TD(wlvlc) + TD(wlvlt) + TD(INPUT(Id=f"use_arti-{char}", type='checkbox', Class='save', checked='checked')) + TD(BUTTON(strings["add"], Class='arti_list text_button', data_id=f"arti-{char}")) + TD(DIV(Id=f"arti-{char}", Class=f'arti_span')) , data_id=f"check-{char}", Class='unchecked', data_color=characters[char]['element'], data_weapon=characters[char]['weapon'] ) # set up traveler base row # set up level select char = 'traveler' lvlc = SELECT(Id=f"level_c-{char}", Class=f"{char} save") lvlt = SELECT(Id=f"level_t-{char}", Class=f"{char} save") for lvl in [lvlc, lvlt]: for c, val in [(0, "1"), (1, "20"), (11, "20 A"), (2, "40"), (12, "40 A"), (3, "50"), (13, "50 A"), (4, "60"), (14, "60 A"), (5, "70"), (15, "70 A"), (6, "80"), (16, "80 A"), (7, "90")]: lvl <= OPTION(f"{val}", value=c) # Set up weapon select ws = SELECT(Id=f"weapon-{char}", data_id=f"select-{char}", Class=f'weapon {char} save') ws <= OPTION('--', value='--') sort_dict_wep = {} for item in weapons[characters[char]['weapon']]: if weapons[characters[char]['weapon']][item]['wam'] != 'unk': sort_dict_wep[strings[item]] = item else: if f"missing-{item}" not in doc: doc['missing'] <= LI(strings[item], Id=f"missing-{item}") for k in sorted(sort_dict_wep): ws <= OPTION(k, value=sort_dict_wep[k]) wlvlc = SELECT(Id=f"weapon_c-{char}", Class=f"{char} save") wlvlt = SELECT(Id=f"weapon_t-{char}", Class=f"{char} save") for lvl in [wlvlc, wlvlt]: for c, val in [(0, "1"), (1, "20"), (11, "20 A"), (2, "40"), (12, "40 A"), (3, "50"), (13, "50 A"), (4, "60"), (14, "60 A"), (5, "70"), (15, "70 A"), (6, "80"), (16, "80 A"), (7, "90")]: lvl <= OPTION(f"{val}", value=c) # Create table row for character t <= TR( TD(INPUT(Id=f"check-{char}", type='checkbox', data_id=f"check-{char}", Class='char_select save')) + TD(IMG(src=f"img/{char}.png", alt=strings[char], title=strings[char], loading="lazy")) + TD(lvlc) + TD(lvlt) + TD() + TD() + TD() + TD() + TD() + TD() + TD(ws) + TD(wlvlc) + TD(wlvlt) + TD(INPUT(Id=f"use_arti-{char}", type='checkbox', Class='save', checked='checked')) + TD(BUTTON(strings["add"], Class='arti_list text_button', data_id=f"arti-{char}")) + TD(DIV(Id=f"arti-{char}", Class=f'arti_span')) , data_id=f"check-{char}", Class='unchecked', data_color='multi', data_weapon=characters[char]['weapon'] ) # set up traveler anemo/geo row for char in sorted(traveler_talent): ele = char.split('_')[1] # Set up talent select t1c = SELECT(Id=f"talent_1_c-{char}", Class=f"{char} save") t1t = SELECT(Id=f"talent_1_t-{char}", Class=f"{char} save") t2c = SELECT(Id=f"talent_2_c-{char}", Class=f"{char} save") t2t = SELECT(Id=f"talent_2_t-{char}", Class=f"{char} save") t3c = SELECT(Id=f"talent_3_c-{char}", Class=f"{char} save") t3t = SELECT(Id=f"talent_3_t-{char}", Class=f"{char} save") for st in [t1t, t1c, t2t, t2c, t3t, t3c]: for cost in costs['talent']: st <= OPTION(cost) # Create table row for character t <= TR( TD(INPUT(Id=f"check-{char}", type='checkbox', data_id=f"check-{char}", Class='char_select save')) + TD(IMG(src=f"img/{char}.png", alt=strings['traveler'], title=strings['traveler'], loading="lazy")) + TD() + TD() + TD(t1c) + TD(t1t) + TD(t2c) + TD(t2t) + TD(t3c) + TD(t3t) + TD() + TD() + TD() + TD() + TD() + TD() , data_id=f"check-{char}", Class='unchecked', data_color=ele, data_weapon=characters['traveler']['weapon'] ) doc['character_list'] <= t
def usersLoaded(req): users = loads(req.text) container = DIV() container <= H2('Edycja zadania') form = FORM(method='PATCH', action='#') input0 = INPUT(name='id', type='hidden', value=task_details['id'], id='id_field') form <= input0 row1 = DIV() row1.class_name = 'row' cell11 = DIV() cell11.class_name = 'large-6 columns' label11 = LABEL('Nazwa') input11 = INPUT(placeholder='Nazwa zadania', type='text', value=task_details['name'], name='name', id='name_field') label11 <= input11 cell11 <= label11 error_panel1 = DIV(id='name_error') error_panel1.class_name = 'panel error' cell11 <= error_panel1 row1 <= cell11 row2 = DIV() row2.class_name = 'row' cell2 = DIV() cell2.class_name = 'large-6 columns' label2 = LABEL('Opis') input2 = INPUT(placeholder='Opis zadania', name='description', id='description_field', type='text') input2.value = task_details['description'] label2 <= input2 cell2 <= label2 row2 <= cell2 cell3 = DIV() cell3.class_name = 'large-6 columns' label3 = LABEL('Przypisane do') input3 = SELECT(name='assignee', id='assignee_field') input3 <= OPTION('---', value=None) for user in users: input3 <= OPTION(user['username'], value=getApiLink('users', user['id'])) input3.value = task_details['assignee'] label3 <= input3 cell3 <= label3 row1 <= cell3 cell7 = DIV() cell7.class_name = 'large-6 columns' label7 = LABEL('Termin wykonania') input7 = INPUT(name='deadline', id='deadline_field', placeholder='yyyy-mm-dd', type='text') input7.value = task_details['deadline'] if task_details['deadline'] else '' label7 <= input7 cell7 <= label7 error_panel7 = DIV(id='deadline_error') error_panel7.class_name = 'panel error' cell7 <= error_panel7 row2 <= cell7 row3 = DIV() row3.class_name = 'row' cell33 = DIV() cell33.class_name = 'large-6 columns' label33 = LABEL('Trudność') input33 = SELECT(name='difficulty', id='difficulty_field') input33 <= OPTION('---', value='None') input33 <= OPTION('łatwe', value='easy') input33 <= OPTION('średnie', value='intermediate') input33 <= OPTION('trudne', value='hard') if task_details['difficulty'] and task_details['difficulty'] in ('easy', 'intermediate', 'hard'): input33.value = task_details['difficulty'] label33 <= input33 cell33 <= label33 cell34 = DIV() cell34.class_name = 'large-6 columns' label34 = LABEL('') label34 <= BR() input34 = BUTTON('Archiwizuj', id='archive_task', data_task_id=task_details['id']) input34.class_name = 'button tiny' label34 <= input34 cell34 <= label34 row3 <= cell33 row3 <= cell34 input34.bind('click', archiveTask) row6 = DIV() row6.class_name = 'row' cell6 = DIV() cell6.class_name = 'large-12 columns' cell6.id = 'comments-container' cell6 <= H4('Komentarze') def appendCommentToDom(author, when, content): length = len(cell6.get(selector='.comment')) colour = '' if length % 2 == 0 else ' callout' #colour = '' panel = DIV() panel.class_name = 'panel comment' + colour panel <= B('{0} dnia {1}'.format(author, when)) panel <= P(content) cell6 <= panel if len(task_details['comments']) == 0: panel = DIV() panel.class_name = 'panel' panel <= P('No comments') cell6 <= panel else: i = 0 for comment in task_details['comments']: author = [user['username'] for user in users if getApiLink('users', user['id']) == comment['author']].pop() when = comment['created_at'] content = comment['content'] appendCommentToDom(author, when, content) row6 <= cell6 row5 = DIV() row5.class_name = 'row' cell5 = DIV() cell5.class_name = 'large-12 columns' label5 = LABEL('Skomentuj') input5 = TEXTAREA(placeholder='Treść komentarza', name='comment', id='comment_field') label5 <= input5 cell5 <= label5 comment_btn = A('Dodaj komentarz', href='#') comment_btn.class_name = 'button tiny' cell5 <= comment_btn row5 <= cell5 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 = '' comment_btn.bind('click', addComment) row4 = DIV() row4.class_name = 'row' cell4 = DIV() cell4.class_name = 'large-12 columns' submit_btn = A('Zapisz zmiany', type='submit', href='#') submit_btn.class_name = 'button tiny' cell4 <= submit_btn row4 <= cell4 form <= row1 form <= row2 form <= row3 form <= row4 form <= row6 form <= row5 container <= form for i in range(1, 6): colour_name = 'colour{0}'.format(i) if str(i) in task_details['colours']: document[colour_name].class_name = 'colour-btn checked' else: document[colour_name].class_name = 'colour-btn' #/api/tasks/ 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 submit_btn.bind('click', on_submit) show_modal(container)