Skip to content

Commit 0d35220

Browse files
authored
Merge pull request #758 from AnswerDotAI/toast_fix
Resolves #712
2 parents 08dbd56 + f400112 commit 0d35220

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

fasthtml/toaster.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,25 @@
3333
.fh-toast-error { background-color: #F44336; }
3434
"""
3535

36+
js = '''htmx.onLoad(() => {
37+
if (!htmx.find('#fh-toast-container')) {
38+
const ctn = document.createElement('div');
39+
ctn.id = 'fh-toast-container';
40+
document.body.appendChild(ctn);
41+
}
42+
});'''
43+
3644
def Toast(message: str, typ: str = "info", dismiss: bool = False, duration:int=5000):
3745
x_btn = Button('x', cls="fh-toast-dismiss", onclick="htmx.remove(this?.parentElement);") if dismiss else None
38-
return Div(Span(message), x_btn, cls=f"fh-toast fh-toast-{typ}", hx_on_transitionend="setTimeout(() => this?.remove(), %d);" % duration)
46+
return Div(Span(message), x_btn, cls=f"fh-toast fh-toast-{typ}", hx_on_transitionend=f"setTimeout(() => this?.remove(), {duration});")
3947

4048
def add_toast(sess, message: str, typ: str = "info", dismiss: bool = False):
4149
assert typ in ("info", "success", "warning", "error"), '`typ` not in ("info", "success", "warning", "error")'
4250
sess.setdefault(sk, []).append((message, typ, dismiss))
4351

4452
def render_toasts(sess):
4553
toasts = [Toast(msg, typ, dismiss, sess['toast_duration']) for msg, typ, dismiss in sess.pop(sk, [])]
46-
return Div(*toasts, id=tcid, hx_swap_oob='afterbegin')
54+
return Div(*toasts, hx_swap_oob=f'beforeend:#{tcid}')
4755

4856
def toast_after(resp, req, sess):
4957
if sk in sess and (not resp or isinstance(resp, (tuple,FT,FtResponse))):
@@ -52,5 +60,5 @@ def toast_after(resp, req, sess):
5260

5361
def setup_toasts(app, duration=5000):
5462
app.state.toast_duration = duration
55-
app.hdrs += [Style(toast_css)]
63+
app.hdrs += [Style(toast_css), Script(js)]
5664
app.after.append(toast_after)

0 commit comments

Comments
 (0)