Skip to content

Commit 67b9665

Browse files
committed
Add reorder
1 parent 21269f8 commit 67b9665

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

examples/adv_app2.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
db = database(':memory:')
99

10+
11+
1012
class User: name:str; pwd:str
1113

1214
class Todo:
@@ -42,7 +44,7 @@ def user_auth_before(req, sess):
4244
user_auth_before,
4345
skip=[r'/favicon\.ico', r'/static/.*', r'.*\.css', r'.*\.js', '/login']
4446
)
45-
app, rt = fast_app(hdrs=Theme.blue.headers(),before=beforeware)
47+
app, rt = fast_app(hdrs=Theme.blue.headers()+[SortableJS('.sortable'),],before=beforeware)
4648

4749
# Authentication
4850
login_redir = Redirect('/login')
@@ -68,7 +70,7 @@ def post(login:Login, sess):
6870
sess['auth'] = u.name
6971
return Redirect('/')
7072

71-
@app.get("/logout")
73+
@rt
7274
def logout(sess):
7375
del sess['auth']
7476
return login_redir
@@ -81,7 +83,7 @@ def index(auth):
8183
add = Form(Group(new_inp, Button("Add")),
8284
hx_post=add_todo, target_id='todo-list', hx_swap="afterbegin")
8385
frm = Form(*db.todos(order_by='priority'),
84-
id='todo-list', cls='sortable', hx_post="/reorder", hx_trigger="end")
86+
id='todo-list', cls='sortable', hx_post=reorder, hx_trigger="end")
8587

8688
card = Card(Ul(frm), header=add, footer=Div(id='current-todo'))
8789
return Titled(f"{auth}'s Todo list", Container(top, card))
@@ -91,7 +93,17 @@ def add_todo(todo:Todo, auth):
9193
new_inp = LabelInput('Title', id="new-title", name="title", placeholder="New Todo", hx_swap_oob='true')
9294
# `insert` returns the inserted todo, which is appended to the start of the list, because we used
9395
# `hx_swap='afterbegin'` when creating the todo list form.
94-
return db.todos.insert(todo), new_inp
96+
return db.todos.insert(todo), new_inp
97+
98+
@rt
99+
def reorder(id:list[int]):
100+
for i,id_ in enumerate(id): db.todos.update({'priority':i}, id_)
101+
# HTMX by default replaces the inner HTML of the calling element, which in this case is the todo list form.
102+
# Therefore, we return the list of todos, now in the correct order, which will be auto-converted to FT for us.
103+
# In this case, it's not strictly necessary, because sortable.js has already reorder the DOM elements.
104+
# However, by returning the updated data, we can be assured that there aren't sync issues between the DOM
105+
# and the server.
106+
return tuple(db.todos(order_by='priority'))
95107

96108

97109
serve()

0 commit comments

Comments
 (0)