Last active
May 12, 2022 21:33
-
-
Save dominicfreeston/b2b58236752b419fd19cd7d982e114bb to your computer and use it in GitHub Desktop.
Reload browser on file change (MacOS/AppleScript/babashka)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bb | |
(require '[babashka.pods :as pods]) | |
(pods/load-pod 'org.babashka/fswatcher "0.0.3") | |
(require '[pod.babashka.fswatcher :as fw]) | |
(def app (or (second *command-line-args*) "Safari")) | |
(println "will reload" app) | |
(def script | |
(if (= app "Safari") | |
;; This version only works with Safari, | |
;; but might be more robust and requires fewer permissions | |
(str "tell application \"" app "\"\n" | |
"set URL of document 1 to URL of document 1\n" | |
"end tell\n") | |
;; This script temporarily brings the target app to the front, | |
;; which could have unintended side-effects, but should work in all browsers | |
;; It does also bring the app to the front which might actually be desirable | |
(str "set old to (path to frontmost application as text)\n" | |
"activate application \"" app "\"\n" | |
"tell application \"System Events\" to keystroke \"r\" using command down\n" | |
"activate application old\n"))) | |
(defn reload [] | |
(println "reloading...") | |
(shell/sh "osascript" "-e" script)) | |
;; This implements a debounce mechanism where we want to | |
;; delay triggering the reload until we stop receiving events. | |
(def reload-op (atom nil)) | |
(defn trigger-reload [_] | |
(let [[old _] (reset-vals! reload-op (future (Thread/sleep 20) (reload)))] | |
(when old (future-cancel old)))) | |
(let [folder (first *command-line-args*)] | |
(fw/watch folder | |
trigger-reload | |
{:delay-ms 0 :recursive true}) | |
(println "watching" (str (fs/canonicalize folder)))) | |
@(promise) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment