Exemple #1
0
def homePage():
    return group(
        DIV(Class=
            "container d-flex flex-column justify-content-center align-items-center",
            style={"height": "100vh"}),
        [
            H1("Breact: A python framework for single page webapps",
               Class="text-center"),
            P('''
            This app was coded in python in Breact. Look in the inspector, and you will see
            <br>
            <code>&lt;script src="text/python" &gt; </code>
        ''',
              Class="text-center"),

            # P('''
            #     Breact is similar to react,
            #     with components and state. The main difference, however, is that
            #     Breact doesn't have a virtual dom; instead, each stateful element
            #     (element that uses setState) is assigned a unique id and is retrieved
            #     and changed when necessary. Breact is very lightweight- the main base
            #     class file is at around 40 lines of code; but that's just because some parts of react;
            #     lifecycle methods, or stateful functional components, haven't been implemented yet.
            # ''', Class="text-center"),
            H3("Sample Apps:"),
            Link("/todo").render(
                BUTTON("Simple Todolist", Class="btn btn-primary m-2")),
            Link('/quiz').render(
                BUTTON("Small Quiz", Class="btn btn-primary m-2")),
            Link('/playground').render(
                BUTTON("A Little Playground", Class="btn btn-primary m-2")),
            Link('/router-playground').render(
                BUTTON("Router Playground", Class="btn btn-warning m-2"))
        ])
Exemple #2
0
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)
Exemple #3
0
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)
Exemple #4
0
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 init_page():
    check_visit()
    pages = ['Table', 'Config']  # , 'About', 'Changelog']
    for c, page in enumerate(pages):
        doc['buttons'] <= BUTTON(
            page,
            data_id=page,
            Class=f'page{" current_tab" if not c else ""}',
            Id=f'b_{page}')
        if c:
            doc['pages'] <= SECTION(Id=page)
            doc[page].style.display = 'none'
    init_options()
    init_table()
    #	init_about()
    #	init_change()
    doc["loading"].style.display = "none"

    # Make it so navigation buttons work
    @bind('.page', 'click')
    def change_page(ev):
        val = ev.target['data-id']
        # currently unable to create an event to trigger the template
        if val == 'Table':
            doc.getElementById('nav_target').click()
        doc[val].style.display = 'block'
        doc[f'b_{val}'].attrs['class'] = 'current_tab page'
        idx = pages.index(val)
        for i in pages[:idx] + pages[idx + 1:]:
            doc[i].style.display = 'none'
            doc[f'b_{i}'].attrs['class'] = 'page'
Exemple #6
0
    def update(self, one_state_change=False):
        if self.state["question"] >= len(QUIZ_CONTENT):
            print("Reached!")
            app = group(DIV(Class="m-3"), [
                H1(f"Correct: {self.state['correct']}"),
                H1(f"Wrong: {self.state['wrong']}"), reset := BUTTON(
                    "reset", Class="btn btn-danger")
            ])

            @bind(reset, "click")
Exemple #7
0
def init_page():
	create_league_list()
	create_base_list()
	pages = ['Main', 'Weights', 'Flags', 'About', 'Changelog']
	for c, page in enumerate(pages):
		doc['buttons'] <= BUTTON(page, data_id=page, Class=f'page{" current_tab" if not c else ""}', Id=f'b_{page}')
		doc['pages'] <= SECTION(Id=page)
		if c:
			doc[page].style.display = 'none'

	data = [('includeDelve', 'Include Precursor Emblem mods'), ('NoSearingImplicitMods', 'Ignore Searing Exarch only Implicit Mods'), ('NoTangledImplicitMods', 'Ignore Eater of Worlds only Implicit Mods'), ('NoSynthImplicitMods', 'Ignore Synth only Implicit Mods'), ('NoCorruptImplicitMods', 'Ignore Corruption only Implicit Mods'), ('NoImplicitMods', 'Ignore All Implicit Mods including corrupt and synth'), ('PseudoMods', 'Use PseudoMods in Search'), ('IgnoreCastSpeed', 'Set Cast Speed Weight to 0'), ('IgnoreAttackSpeed', 'Set Attack Speed Weight to 0')]  # ('NoCraftedMods', 'Ignore Crafted Mods'),
	t = make_table(data, 1, 'ignore')
	doc['searchflags'] <= STRONG('Options:') + ' choices that affect type of returned mods' + BR() + t + BR()

	init_about()
	init_flags()
	init_change()

	doc["query"].style.display = "none"
	doc["notice"].style.display = "none"
	doc["414by"].style.display = "none"
	b_generate = BUTTON("Generate Query")
	b_generate.bind("click", generate_query)
	doc["generate"] <= b_generate
	process_querystring()
	init_main()
	doc["loading"].style.display = "none"

	# Make it so navigation buttons work
	@bind('.page', 'click')
	def change_page(ev):
		val = ev.target['data-id']
		if val == 'Main':
			init_main()
		doc[val].style.display = 'block'
		doc[f'b_{val}'].attrs['class'] = 'current_tab page'
		idx = pages.index(val)
		for i in pages[:idx] + pages[idx+1:]:
			doc[i].style.display = 'none'
			doc[f'b_{i}'].attrs['class'] = 'page'
def create_table(name):
    global ie_desc_array
    ie_desc_array = []
    #
    m = name_msg_map[name]
    document.title = f'{g.release}: {m.id} {m.name}'
    document['title'] <= document.title
    #
    button = BUTTON('show IE description')
    document['top'] <= button
    button.bind('click', toggle_ie_desc)
    #
    document['top'] <= SPAN(' ')
    document['top'] <= A('Index', href='')
    document['output'] <= PRE(m.id + ' ' + m.name + '\n' + m.definition,
                              Class='definition')
    table = TABLE(id='msgtable')
    document['output'] <= table
    for r, row in enumerate(m.aoa):
        tr = TR(Class=f'r{r}')
        table <= tr
        for c, v in enumerate(row):
            title = ''
            if r == 0 and c in (2, 3, 4, 5):
                title, v = v, ''
            elif c == 2:
                lst = v.replace('\n', ' ').split(' ')
                lst2 = [ie for ieid, ie in id_ie_map.items() if ieid in lst]
                if len(lst2) == 1:
                    ie = lst2[0]
                    title = f'{ie.id} {ie.name}\n{ie.definition}'
                    v = A(f'{ie.id}', href=f'#ie{ie.id}')
                ie_desc_array.append(title)
            elif r != 0 and c == 6:
                if v:
                    v = DIV(v) + DIV('', Class='iedescdiv', needsep='y')
                else:
                    v = DIV('', Class='iedescdiv', needsep='n')
            tr <= TD(v, title=title, Class=f'c{c}')
Exemple #9
0
def custom_menu(ev):
    if 'data-id' in ev.target.attrs and 'menu-item' in ev.target.attrs[
            'class'] and 'vertical-menu' in ev.target.attrs['class']:
        if f"{ev.target.attrs['data-id']}-{ev.target.id}" not in doc:
            b = BUTTON(
                strings[ev.target.id],
                Class=
                f'text_button saved_arti {ev.target.attrs["data-id"].split("-")[1]}',
                Id=f"{ev.target.attrs['data-id']}-{ev.target.id}",
                data_arti=ev.target.id)
            b.bind('click', delete_me)
            doc[ev.target.attrs["data-id"]] <= b
            grind_table_state['artifacts'].add(
                f"{ev.target.attrs['data-id']}-{ev.target.id}")
            set_storage(f"{ev.target.attrs['data-id']}-{ev.target.id}", 'y')
            if ev.target.attrs['data-id'].split(
                    '-')[1] in grind_table_state['arti_check']:
                calculate_change()
        ev.stopPropagation()
    if 'vertical-menu' in doc:
        del doc['vertical-menu']
    doc.unbind('mouseclick', custom_menu)
Exemple #10
0
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
Exemple #11
0
    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_table(self):
     dindex.style.display = 'none'
     dtop.clear()
     doutput.clear()
     section = self.get_section()
     aoa = section.aoa
     #
     document.title = f'{get_protocol_name()} {section.name}'
     dtop <= SPAN(self.release)
     dtop <= SPAN(A('Index', href='#'))
     #
     b = BUTTON('copy tree')
     b.bind('click', ready.copy_tree)
     dtop <= SPAN(b)
     #
     b = BUTTON('export xlsx')
     b.bind('click', self.export_xlsx)
     dtop <= SPAN(b)
     #
     b = BUTTON('table view')
     b.bind('click', self.change_view)
     dtop <= SPAN(b)
     #
     b = BUTTON('Popup On')
     b.bind('click', ready.button_popup)
     dtop <= SPAN(b)
     b.style.backgroundColor = 'lightgreen'
     #
     dtop <= SPAN(f'{section.id} {section.name}')
     self.create_prev_next()
     #
     table = TABLE(Class='asn1tree', tview='tree', core='')
     head = [
         "", "", 'IE', 'Need', 'Refer', 'Type', 'Description', 'Crit',
         'Assign'
     ]
     table <= TR([TD(B(v)) for v in head])
     table.rows[0].cells[6].className = 'desc'
     #
     for row in aoa:
         flag, level, ie, need, udf, vrange, desc, crit, assign = row
         pad, ie = get_pad_and_ie(ie)
         tr = TR()
         tr <= TD(flag, Class='flag')
         tr <= TD(level)
         hasdesc = 'hasdesc' if desc else ''
         tr <= TD(
             SPAN(pad,
                  Class='iepad',
                  treepad=pad,
                  tablepad='>' * level + ' ') +
             SPAN(ie, Class='ie', desc=hasdesc))
         tr <= TD(need)
         if udf:
             tr <= TD(A(udf, href=f'#{udf}'))
         else:
             tr <= TD()
         tr <= TD(vrange, Class='vrange')
         tr <= TD(desc, Class='desc')
         tr <= TD(crit)
         tr <= TD(assign)
         table <= tr
     for tr in table.rows:
         tr <= TD(tr.rowIndex)
     doutput <= table
     ready.ready_table(table)
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_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
Exemple #16
0
        question = elementOn['question']
        ans = elementOn['answer']

        def correctWrong():
            if "prev" in self.state:
                if self.state["prev"] == True:
                    return H3("Your answer is correct", Class="text-success")
                return H3("Your answer was wrong", Class="text-danger")
            return DIV()

        app = group(DIV(Class="container", style={"minWidth": "60vw"}), [
            H1(question + ":"),
            correctWrong(),
            group(DIV(Class="container"), [
                group(DIV(Class="row"), [
                    option1 := BUTTON(options[0],
                                      Class="col-sm btn btn-danger m-2"),
                    option2 := BUTTON(options[1],
                                      Class="col-sm btn btn-info m-2"),
                ]),
                group(DIV(Class="row"), [
                    option3 := BUTTON(options[2],
                                      Class="col-sm btn btn-warning m-2"),
                    option4 := BUTTON(options[3],
                                      Class="col-sm btn btn-success m-2"),
                ])
            ])
        ])

        def submission(option):
            if options[option] == ans:
                correct = True
Exemple #17
0
def init_page():
    global char_dict
    char_keys = []
    for elt in doc.get(selector=".amber"):
        char_keys.append((elt.id.split('-')[0], elt.value))
    char_dict = {k: int(v) if v.isnumeric() else v for k, v in char_keys}

    for elt in doc.get(selector='.char_select'):
        name = elt.id.split('-')[1]
        grind_table_state['characters'][name] = char_dict.copy()
        grind_table_state['arti_check'].add(name)

    # for tracking state without querying the DOM constantly
    grind_table_state['user'][f"xp"] = 0
    grind_table_state['user'][f"xp_sub_1"] = 0
    grind_table_state['user'][f"xp_sub_0"] = 0
    grind_table_state['user'][f"wep_xp"] = 0
    grind_table_state['user'][f"wep_xp_sub_1"] = 0
    grind_table_state['user'][f"wep_xp_sub_0"] = 0
    grind_table_state['user'][f"mora"] = 0
    grind_table_state['total'][f"xp"] = 0
    grind_table_state['total'][f"wep_xp"] = 0
    grind_table_state['total'][f"mora"] = 0
    for item in doc.get(selector=f'input[type=number].save'):
        item = item.id.split('-')[0]
        grind_table_state['user'][item] = 0
        grind_table_state['total'][item] = 0

    # load any saved values
    for k, v in list_storage():
        if v == 'checked' and 'check' in k:
            sub_key, char = k.split('-')
            grind_table_state['checked'].add(char)
            doc[k].checked = True
            for elt in doc.get(selector=f'TR[data-id="{k}"]'):
                elt.attrs['class'] = 'checked'
        elif v == 'unchecked':
            sub_key, char = k.split('-')
            grind_table_state['arti_check'].discard(char)
            doc[k].checked = False
        elif 'select' in v:
            if '-' in k:
                sub_key, char = k.split('-')
            else:
                sub_key = k
                char = ''
            val = v.split('-')[1]
            doc[k].value = val
            if char:
                grind_table_state['characters'][char][sub_key] = int(
                    val) if val.isnumeric() else val
        elif v == 'y':
            target, ev_id = k.rsplit('-', maxsplit=1)
            b = BUTTON(strings[ev_id],
                       Class=f'text_button saved_arti {target.split("-")[1]}',
                       Id=f"{target}-{ev_id}",
                       data_arti=ev_id)
            b.bind('click', delete_me)
            doc[target] <= b
            grind_table_state['artifacts'].add(f"{target}-{ev_id}")
        elif '-user' in k:
            grind_table_state['user'][k.split('-')[0]] = int(v)
            doc[k].value = v
        else:
            print(f"Invalid stored data: {k}, {v}")
    # finish updating page state after loading data
    calculate_change()
    update_visible()
    # add navigation buttons
    pages = ['characters', 'inventory',
             'information']  # , 'About', 'Changelog']
    for c, page in enumerate(pages):
        doc['nav_buttons'] <= BUTTON(
            page.capitalize(),
            data_id=page,
            Class=f'page{" current_tab" if not c else ""}',
            Id=f'b_{page}')

    # Make it so navigation buttons work
    @bind('.page', 'click')
    def change_page(ev):
        global current_page
        l_val = ev.target['data-id']
        current_page = l_val
        calculate_change()
        doc[l_val].style.display = 'block'
        doc[f'b_{l_val}'].attrs['class'] = 'current_tab page'
        idx = pages.index(l_val)
        for i in pages[:idx] + pages[idx + 1:]:
            doc[i].style.display = 'none'
            doc[f'b_{i}'].attrs['class'] = 'page'
        if ev.target.id == "back_login
            hide login id div
        elif ev.target.id == "back_register
            hide register id div
    """
    if ev.target.id == "back_login":
        doc['login'].style.display = "none"
        doc['welcome'].style.display = "block"
    elif ev.target.id == "back_register":
        doc['register'].style.display = "none"
        doc['welcome'].style.display = "block"


"""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")
 def create_tree(self):
     dindex.style.display = 'none'
     dtop.clear()
     doutput.clear()
     aoa = self.get_aoa()
     #
     document.title = f'{get_protocol_name()} {self.anchor}'
     document.title = f'{get_protocol_name()} {self.get_short_title()}'.strip()
     dtop <= SPAN(self.release)
     dtop <= SPAN(A('Index', href='#'))
     dtop <= SPAN(A('Search', href=f'#search'))
     dtop <= SPAN(A('ASN1', href=f'{self.asn1html}#{self.anchor}'))
     #
     b = BUTTON('copy tree')
     b.bind('click', ready.copy_tree)
     dtop <= SPAN(b)
     #
     b = BUTTON('export xlsx')
     b.bind('click', self.export_xlsx)
     dtop <= SPAN(b)
     #
     b = BUTTON('table view')
     b.bind('click', self.change_view)
     dtop <= SPAN(b)
     #
     b = BUTTON('Popup On')
     b.bind('click', ready.button_popup)
     dtop <= SPAN(b)
     b.style.backgroundColor = 'lightgreen'
     #
     t = int((self.get_nrows()/1000) * 2 + 1 )
     t = f'{t}s'
     b = BUTTON(f'expand all ({self.get_nrows()} rows, need {t})')
     b.bind('click', self.click_expand_all)
     dtop <= SPAN(b)
     #
     b = BUTTON('Hidden Prefix')
     b.bind('click', self.click_hidden_prefix)
     dtop <= SPAN(b)
     #
     dtop <= SPAN(f'{self.anchor}')
     #
     table = TABLE(Class='asn1tree', tview='tree')
     self.creat_head_row(table)
     for row in aoa:
         table <= self.create_tree_tr(row)
     doutput <= table
     for tr in table.rows:
         tr.cells[-1].html = tr.rowIndex
     ready.ready_table(table)
Exemple #20
0
                            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)