Skip to content

Commit 131b5a5

Browse files
authored
Merge pull request #588 from AnswerDotAI/js-script-formatting-cleanup
use % notation instead of .format in toast js & livereload js
2 parents 6d602ef + a50331d commit 131b5a5

File tree

2 files changed

+31
-37
lines changed

2 files changed

+31
-37
lines changed

fasthtml/live_reload.py

Lines changed: 15 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,25 @@
44
__all__ = ["FastHTMLWithLiveReload"]
55

66

7-
LIVE_RELOAD_SCRIPT = """
8-
(function() {{
9-
var socket = new WebSocket(`ws://${{window.location.host}}/live-reload`);
10-
var maxReloadAttempts = {reload_attempts};
11-
var reloadInterval = {reload_interval}; // time between reload attempts in ms
12-
socket.onclose = function() {{
7+
def LiveReloadJs(reload_attempts:int=1, reload_interval:float=1000., **kwargs):
8+
src = """
9+
(function() {
10+
var socket = new WebSocket(`ws://${window.location.host}/live-reload`);
11+
var maxReloadAttempts = %s;
12+
var reloadInterval = %s; // time between reload attempts in ms
13+
socket.onclose = function() {
1314
let reloadAttempts = 0;
14-
const intervalFn = setInterval(function(){{
15+
const intervalFn = setInterval(function(){
1516
window.location.reload();
1617
reloadAttempts++;
1718
if (reloadAttempts === maxReloadAttempts) clearInterval(intervalFn);
18-
}}, reloadInterval);
19-
}}
20-
}})();
19+
}, reloadInterval);
20+
}
21+
})();
2122
"""
23+
return Script(src % (reload_attempts, reload_interval))
2224

23-
24-
async def live_reload_websocket(websocket): await websocket.accept()
25+
async def live_reload_ws(websocket): await websocket.accept()
2526

2627
class FastHTMLWithLiveReload(FastHTML):
2728
"""
@@ -47,19 +48,8 @@ class FastHTMLWithLiveReload(FastHTML):
4748
Run:
4849
serve()
4950
"""
50-
LIVE_RELOAD_ROUTE = WebSocketRoute("/live-reload", endpoint=live_reload_websocket)
51-
5251
def __init__(self, *args, **kwargs):
53-
# Create the live reload script to be injected into the webpage
54-
self.LIVE_RELOAD_HEADER = Script(
55-
LIVE_RELOAD_SCRIPT.format(
56-
reload_attempts=kwargs.get("reload_attempts", 1),
57-
reload_interval=kwargs.get("reload_interval", 1000),
58-
)
59-
)
60-
6152
# "hdrs" and "routes" can be missing, None, a list or a tuple.
62-
kwargs["hdrs"] = [*(kwargs.get("hdrs") or []), self.LIVE_RELOAD_HEADER]
63-
kwargs["routes"] = [*(kwargs.get("routes") or []), self.LIVE_RELOAD_ROUTE]
53+
kwargs["hdrs"] = [*(kwargs.get("hdrs") or []), LiveReloadJs(**kwargs)]
54+
kwargs["routes"] = [*(kwargs.get("routes") or []), WebSocketRoute("/live-reload", endpoint=live_reload_ws)]
6455
super().__init__(*args, **kwargs)
65-

fasthtml/toaster.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,27 +31,31 @@
3131
.fh-toast-error { background-color: #F44336; }
3232
"""
3333

34-
toast_js = """
35-
export function proc_htmx(sel, func) {{
36-
htmx.onLoad(elt => {{
34+
def ToastJs(duration:float):
35+
duration = int(1000*duration)
36+
src = """
37+
export function proc_htmx(sel, func) {
38+
htmx.onLoad(elt => {
3739
const elements = any(sel, elt, false);
3840
if (elt.matches && elt.matches(sel)) elements.unshift(elt);
3941
elements.forEach(func);
40-
}});
41-
}}
42-
proc_htmx('.fh-toast-container', async function(toast) {{
42+
});
43+
}
44+
proc_htmx('.fh-toast-container', async function(toast) {
4345
await sleep(100);
4446
toast.style.opacity = '0.8';
45-
await sleep({duration});
47+
await sleep(%s);
4648
toast.style.opacity = '0';
4749
await sleep(300);
4850
toast.remove();
49-
}});
51+
});
5052
51-
proc_htmx('.fh-toast-dismiss', function(elem) {{
52-
elem.addEventListener('click', (e) => {{ e.target.parentElement.remove() }});
53-
}});
53+
proc_htmx('.fh-toast-dismiss', function(elem) {
54+
elem.addEventListener('click', (e) => { e.target.parentElement.remove() });
55+
});
5456
"""
57+
return Script(src % (duration,), type="module")
58+
5559

5660
def add_toast(sess, message, typ="info"):
5761
assert typ in ("info", "success", "warning", "error"), '`typ` not in ("info", "success", "warning", "error")'
@@ -65,5 +69,5 @@ def toast_after(resp, req, sess):
6569
if sk in sess and (not resp or isinstance(resp, (tuple,FT,FtResponse))): req.injects.append(render_toasts(sess))
6670

6771
def setup_toasts(app, duration:float=10.):
68-
app.hdrs += (Style(toast_css), Script(toast_js.format(duration=1000*duration), type="module"))
72+
app.hdrs += (Style(toast_css), ToastJs(duration))
6973
app.after.append(toast_after)

0 commit comments

Comments
 (0)