| 1 | module veb |
| 2 | |
| 3 | import time |
| 4 | |
| 5 | // Note: to use live reloading while developing, the suggested workflow is doing: |
| 6 | // `v -d veb_livereload watch --keep run your_veb_server_project.v` |
| 7 | // in one shell, then open the start page of your veb app in a browser. |
| 8 | // |
| 9 | // While developing, just open your files and edit them, then just save your |
| 10 | // changes. Once you save, the watch command from above, will restart your server, |
| 11 | // and your HTML pages will detect that shortly, then they will refresh themselves |
| 12 | // automatically. |
| 13 | |
| 14 | // veb_livereload_server_start records, when the veb server process started. |
| 15 | // That is later used by the /script.js and /current endpoints, which are active, |
| 16 | // if you have compiled your veb project with `-d veb_livereload`, to detect |
| 17 | // whether the web server has been restarted. |
| 18 | const veb_livereload_server_start = time.ticks().str() |
| 19 | |
| 20 | // handle_veb_livereload_current serves a small text file, containing the |
| 21 | // timestamp/ticks corresponding to when the veb server process was started |
| 22 | @[if veb_livereload ?] |
| 23 | fn (mut ctx Context) handle_veb_livereload_current() { |
| 24 | ctx.send_response_to_client('text/plain', veb_livereload_server_start) |
| 25 | } |
| 26 | |
| 27 | // handle_veb_livereload_script serves a small dynamically generated .js file, |
| 28 | // that contains code for polling the veb server, and reloading the page, if it |
| 29 | // detects that the veb server is newer than the veb server, that served the |
| 30 | // .js file originally. |
| 31 | @[if veb_livereload ?] |
| 32 | fn (mut ctx Context) handle_veb_livereload_script() { |
| 33 | res := '"use strict"; |
| 34 | function veb_livereload_checker_fn(started_at) { |
| 35 | fetch("/veb_livereload/" + started_at + "/current", { cache: "no-cache" }) |
| 36 | .then((response) => response.text()) |
| 37 | .then(function (current_at) { |
| 38 | // console.log(started_at); console.log(current_at); |
| 39 | if (started_at !== current_at) { |
| 40 | // the app was restarted on the server: |
| 41 | window.location.reload(); |
| 42 | } |
| 43 | }); |
| 44 | } |
| 45 | const veb_livereload_checker = setInterval(veb_livereload_checker_fn, ${ctx.livereload_poll_interval_ms}, "${veb_livereload_server_start}"); |
| 46 | ' |
| 47 | ctx.send_response_to_client('text/javascript', res) |
| 48 | } |
| 49 | |