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
2627class 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-
0 commit comments