Bookmarklet improvements (#3)

* Remove unused function

* Improve serialisation + loading of bookmarlets

- Drop bookmark link on textarea to edit

* Move serialisation to correct place
This commit is contained in:
Jeroen van Dijk 2021-05-27 12:12:26 +02:00 committed by GitHub
parent d673a5f947
commit 169c9b8717
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -13,14 +13,21 @@
(str ";s.onerror=" onerror)) (str ";s.onerror=" onerror))
";document.body.appendChild(s);")) ";document.body.appendChild(s);"))
(defn append-script-tag [url] (defn pr-code [code-str]
(append-tag :script {:type "application/javascript" :src url})) (let [s (pr-str (str "#_CODE_" code-str "#_CODE_"))]
(str "\"" (subs s 1 (dec (count s))) "\"")))
(defn bookmarklet-href [code] (defn read-code [code]
(read-string (str "\"" code "\"")))
(defn extract-code [code-str]
(second (re-find #"#_CODE_(.+)#_CODE_" code-str)))
(defn bookmarklet-href [code-str]
(str "javascript:(function(){" (str "javascript:(function(){"
"var runCode = function() { "var runCode = function() {
try { try {
scittle.core.eval_string('" code "') scittle.core.eval_string(" (pr-code code-str) ")
} catch (error) { } catch (error) {
console.log('Error in code', error); console.log('Error in code', error);
alert('Error running code, see console') alert('Error running code, see console')
@ -35,6 +42,7 @@
runCode() }" runCode() }"
"})();")) "})();"))
(defn workspace [] (defn workspace []
(let [value (str "; This is the code of your bookmarklet\n" (let [value (str "; This is the code of your bookmarklet\n"
(pr-str '(js/alert "Hello"))) (pr-str '(js/alert "Hello")))
@ -53,6 +61,17 @@
v))))}] v))))}]
[:br] [:br]
[:textarea {:rows 10 :cols 80 [:textarea {:rows 10 :cols 80
:on-drop (fn [e]
(let [bookmarklet (js/decodeURIComponent (.. e -dataTransfer (getData "text")))
cljs-snippet (some-> (extract-code bookmarklet)
read-code)
new-code (if cljs-snippet
(str "; Extracted snippet\n" cljs-snippet)
(str "; Failed to extract snippet\n" bookmarklet))]
(js/console.log "Dropped" bookmarklet)
(set! (.. e -target -value) new-code)
(reset! *code new-code)
(.preventDefault e)))
:on-change (fn [e] (reset! *code (.. e -target -value)))} :on-change (fn [e] (reset! *code (.. e -target -value)))}
value] value]
[:br] [:br]
@ -61,10 +80,8 @@
"or"[:br] "or"[:br]
"Drag the link to the bookmarks bar" [:br] "Drag the link to the bookmarks bar" [:br]
[(fn [] [(fn []
(let [sanitized (->> (clojure.string/split-lines @*code) (remove #(re-find #"\s*;"%)) (clojure.string/join "\n"))] (js/console.log "Loaded", @*code)
(js/console.log "Loaded", sanitized) [(fn [] [:a {:href (bookmarklet-href @*code)} @*bookmark-name])])
[(fn [] [:a {:href (bookmarklet-href sanitized)} @*bookmark-name])] *code]]))
)) *code]]))
(rdom/render [workspace] (.getElementById js/document "app")) (rdom/render [workspace] (.getElementById js/document "app"))