core.cljs 15.3 KB
Newer Older
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
1
(ns booklet.core
2
  (:require [cljs.core.async :refer [>! <!]]
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
3
            [cljsjs.react-bootstrap]
4
            [khroma.idle :as idle]
5
            [khroma.log :as console]
6
            [khroma.runtime :as runtime]
7
            [khroma.storage :as storage]
8
            [khroma.tabs :as tabs]
9
            [khroma.windows :as windows]
10
            [reagent.core :as reagent]
11
            [re-frame.core :refer [dispatch register-sub register-handler subscribe dispatch-sync]])
12 13 14 15 16 17 18 19 20 21 22 23
  (:require-macros [cljs.core.async.macros :refer [go]]
                   [reagent.ratom :refer [reaction]]))


;;;;------------------------------
;;;; Queries
;;;;------------------------------

(defn general-query
  [db path]
  (reaction (get-in @db path)))

24
(register-sub :data general-query)
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
25
(register-sub :ui-state general-query)
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
26
(register-sub :app-state general-query)
27 28 29 30 31 32


;;;;----------------------------
;;;; Functions
;;;;----------------------------

33 34 35 36 37
(defn dispatch-on-press-enter [e d]
  (if (= 13 (.-which e))
    (dispatch d)))


38 39 40 41 42 43 44 45 46 47
(defn filter-tabs
  "Filters out the tabs we will not show or manipulate, for instance, chrome extensions"
  [tabs]
  (remove #(.startsWith (:url %) "chrome") tabs))

(defn group-from-tabs
  "Takes a tabset and returns a new group containing them and some extra data"
  [tabs]
  {:date (.now js/Date)
   :tabs tabs})
48

49 50 51 52 53 54 55
(defn group-label [group]
  (or (:name group) (:date group)))

(def initial-focus-wrapper
  (with-meta identity
             {:component-did-mount #(.focus (reagent/dom-node %))}))

56 57 58 59 60 61
(defn remove-tab
  "Removed a tab from a collection by id"
  [col id]
  (remove #(= (:id %) id) col))


62 63 64 65 66

;;;;----------------------------
;;;; Handlers
;;;;----------------------------

Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
(register-handler
  :app-state-item
  (fn [app-state [_ path item]]
    (assoc-in app-state path item)))


(register-handler
  :data-import
  (fn [app-state [_ json-data]]
    (let [current  (:data app-state)
          new-data (clojure.walk/keywordize-keys (js->clj (.parse js/JSON json-data)))]
      (-> app-state
          (assoc :data (merge current new-data))
          (assoc-in [:ui-state :section] :groups)
          (assoc-in [:app-state :import] nil))
82 83 84 85 86 87 88
      )))

(register-handler
  :data-set
  (fn [app-state [_ key item]]
    (storage/set {key item})
    (assoc-in app-state [:data key] item)
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
89 90 91
    ))


92 93 94
(register-handler
  :initialize
  (fn [_ [_ tabs]]
95
    (go (dispatch [:storage-loaded (<! (storage/get))]))
96 97
    {:data     {:tabs tabs}
     :ui-state {:section :monitor}}))
98

99 100 101 102 103 104 105 106 107 108
(register-handler
  :group-add
  (fn [app-state [_]]
    (let [tabs    (get-in app-state [:data :tabs])
          to-save (map (fn [m] (select-keys m [:index :url :id :title :favIconUrl])) tabs)
          groups  (conj (or (get-in app-state [:data :groups]) '())
                        (group-from-tabs to-save))]
      (dispatch [:data-set :groups groups])
      app-state)))

Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
109 110 111 112
(register-handler
  :group-delete-set
  (fn [app-state [_ group]]
    (dispatch [:modal-info-set {:header       "Please confirm"
113
                                :body         (str "Do you want to delete tab group " (group-label group) "?")
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
114 115 116 117
                                :action-label "Kill it"
                                :action       #(do
                                                (dispatch [:modal-info-set nil])
                                                (dispatch [:group-delete group]))}])
118
    app-state))
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
119 120 121 122 123

(register-handler
  :group-delete
  (fn [app-state [_ group]]
    (let [original (get-in app-state [:data :groups])
124
          groups   (remove #(= group %) original)]
125
      (dispatch [:data-set :groups groups])
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
126 127
      app-state)))

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

(register-handler
  :group-edit-set
  (fn [app-state [_ group]]
    (dispatch [:group-label-set (group-label group)])
    (assoc-in app-state [:ui-state :group-edit] group)))


(register-handler
  :group-label-set
  (fn [app-state [_ label]]
    (assoc-in app-state [:ui-state :group-label] label)))

(register-handler
  :group-update
  (fn [app-state [_ old-group new-group]]
144 145 146
    (dispatch [:data-set :groups (->> (get-in app-state [:data :groups])
                                      (remove #(= % old-group))
                                      (cons new-group))])
147 148 149
    app-state))


Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
150
(register-handler
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  :idle-state-change
  (fn [app-state [_ message]]
    (let [path    [:app-state :interval]
          handler (get-in app-state path)
          state   (:newState message)]
      (console/log "Idle state change:" state handler)
      (cond
        (and (nil? handler)
             (= state "active")) (assoc-in app-state path (js/setInterval #(dispatch [:snapshot-take]) 60000))
        (and (some? handler)
             (not= state "active")) (do
                                      (js/clearInterval handler)
                                      (assoc-in app-state path nil))
        :else app-state
        ))))


(register-handler
  :log-content
  (fn [app-state [_ content]]
    (console/log "Log event:" content)
    app-state
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
173 174
    ))

175

Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
176 177 178 179 180
(register-handler
  :modal-info-set
  (fn [app-state [_ info]]
    (assoc-in app-state [:ui-state :modal-info] info)))

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

(register-handler
  :snapshot-take
  (fn [app-state [_]]
    (let [path      [:data :snapshots]
          current   (or (get-in app-state path) '())
          tabs      (get-in app-state [:data :tabs])
          new-group (group-from-tabs (map #(select-keys % [:index :url :id :title :favIconUrl]) tabs))
          snapshots (conj current new-group)
          ]
      (console/log "Tick tock snapshot" (.now js/Date) (count snapshots) snapshots)
      (dispatch [:data-set :snapshots snapshots]))
    app-state
    ))


197 198 199
(register-handler
  :storage-loaded
  (fn [app-state [_ data]]
200
    (assoc app-state :data (merge (:data app-state) data))
201 202
    ))

203

204 205 206
(register-handler
  :tab-created
  (fn [app-state [_ msg]]
207
    (console/trace "Created" (:tab msg))
208
    (assoc app-state [:data :tabs] (conj (get-in app-state [:data :tabs]) (:tab msg)))))
209 210 211 212 213


(register-handler
  :tab-updated
  (fn [app-state [_ msg]]
214
    (console/trace "Updated:" msg)
215
    (assoc-in app-state
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
216 217 218 219
              [:data :tabs]
              (-> (get-in app-state [:data :tabs])
                  (remove-tab (:tabId msg))
                  (conj (:tab msg))))
220 221 222 223 224
    ))

(register-handler
  :tab-removed
  (fn [app-state [_ msg]]
225
    (console/trace "Removed:" (:tabId msg) msg)
226
    (assoc-in app-state [:data :tabs] (remove-tab (get-in app-state [:data :tabs]) (:tabId msg)))))
227 228 229 230

(register-handler
  :tab-replaced
  (fn [app-state [_ msg]]
231
    (console/trace "Replaced:" msg)
232 233
    ; We don't need to create a new item for the tab being added, as
    ; we'll also get an "update" message which will add it.
234
    (assoc-in app-state [:data :tabs] (remove-tab (get-in app-state [:data :tabs]) (:removed msg)))))
235

236

Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
237 238 239 240 241 242 243 244 245 246

;;;;------------------------------
;;;; Utils
;;;;------------------------------

(def Modal (reagent/adapt-react-class js/ReactBootstrap.Modal))
(def ModalBody (reagent/adapt-react-class js/ReactBootstrap.ModalBody))
(def ModalFooter (reagent/adapt-react-class js/ReactBootstrap.ModalFooter))
(def ModalHeader (reagent/adapt-react-class js/ReactBootstrap.ModalHeader))

247 248


249 250 251 252 253
;;;;----------------------------
;;;; Components
;;;;----------------------------


254 255
(defn navbar-item [label section current]
  [:li {:class (when (= section current) "active")}
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
256
   [:a {:on-click #(dispatch [:app-state-item [:ui-state :section] section])} label
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    (when (= section current) [:span {:class "sr-only"} "(current)"])]]
  )

(defn navbar []
  (let [section (subscribe [:ui-state :section])]
    (fn []
      [:nav {:class "navbar navbar-default"}
       [:div {:class "container-fluid"}
        [:div {:class "navbar-header"}
         [:button {:type "button", :class "navbar-toggle collapsed", :data-toggle "collapse", :data-target "#bs-example-navbar-collapse-1"}
          [:span {:class "sr-only"} "Toggle navigation"]
          [:span {:class "icon-bar"}]
          [:span {:class "icon-bar"}]
          [:span {:class "icon-bar"}]]
         [:a {:class "navbar-brand", :href "#"} "Brand"]]
        [:div {:class "collapse navbar-collapse", :id "bs-example-navbar-collapse-1"}
         [:ul {:class "nav navbar-nav"}
          [navbar-item "Monitor" :monitor @section]
          [navbar-item "Groups" :groups @section]
          [navbar-item "Snapshots" :snapshots @section]]
         [:form {:class "navbar-form navbar-left", :role "search"}
          [:div {:class "form-group"}
           [:input {:type "text", :class "form-control", :placeholder "Search"}]]
          [:button {:type "submit", :class "btn btn-default"} "Submit"]]
         [:ul {:class "nav navbar-nav navbar-right"}
          [navbar-item "Export" :export @section]
          [navbar-item "Import" :import @section]]]]])))


Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
(defn modal-confirm []
  (let [modal-info (subscribe [:ui-state :modal-info])
        ;; On the next one, we can't use not-empty because (= nil (not-empty nil)), and :show expects true/false,
        ;; not a truth-ish value.
        show?      (reaction (not (empty? @modal-info)))]
    (fn []
      [Modal {:show @show? :onHide #(dispatch [:modal-info-set nil])}
       [ModalHeader
        [:h4 (:header @modal-info)]]
       [ModalBody
        [:div
         (:body @modal-info)]]
       [ModalFooter
        [:button {:type     "reset"
                  :class    "btn btn-default"
                  :on-click #(dispatch [:modal-info-set nil])} "Cancel"]
        [:button {:type     "submit"
                  :class    "btn btn-primary"
                  :on-click (:action @modal-info)} (:action-label @modal-info)]
        ]])))

307
(defn list-tabs [tabs is-history?]
308
  (for [tab (sort-by :index tabs)]
309 310 311 312
    (let [url     (:url tab)
          favicon (:favIconUrl tab)
          action  (if is-history?
                    {:href url :target "_blank"}
313
                    {:on-click #(tabs/activate (:id tab))}
314 315 316 317 318 319 320 321 322 323 324 325 326 327
                    )]
      ^{:key (:id tab)}
      [:tr
       [:td {:class "col-sm-1"} (if-not is-history? (:id tab))]
       [:td {:class "col-sm-6"} [:a
                                 action
                                 (if favicon
                                   [:img {:src    favicon
                                          :width  16
                                          :height 16}])
                                 (:title tab)]]
       [:td {:class "col-sm-5"} url]])))

(defn current-tabs []
328
  (let [tabs (reaction (filter-tabs @(subscribe [:data :tabs])))]
329
    (fn []
330
      [:div
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
331
       [:div {:class "page-header"} [:h2 "Current tabs"]]
332 333 334 335 336 337 338
       [:table {:class "table table-striped table-hover"}
        [:thead
         [:tr
          [:th "#"]
          [:th "Title"]
          [:th "URL"]]]
        [:tbody
339
         (list-tabs @tabs false)]
340
        ]
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
341
       [:a {:class    "btn btn-primary btn-sm"
342
            :on-click #(dispatch [:group-add])} "Save me"]
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
343 344 345 346
       [:a {:class    "btn btn-primary btn-sm"
            :on-click #(go (console/log (<! (storage/get))))} "Get"]
       [:a {:class    "btn btn-primary btn-sm"
            :on-click #(go (console/log "Usage: " (<! (storage/bytes-in-use))))} "Usage"]
347
       ; [:button {:on-click #(storage/clear)} "Clear"]
348 349
       ])))

350
(defn tab-groups []
351 352 353 354
  (let [tab-groups (subscribe [:data :groups])
        group-edit (subscribe [:ui-state :group-edit])
        label      (subscribe [:ui-state :group-label])
        to-list    (reaction (sort-by #(* -1 (:date %)) @tab-groups))]
355 356
    (fn []
      [:div
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
357
       [modal-confirm]
358
       [:div {:class "page-header"} [:h2 "Previous groups"]]
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
       (doall
         (for [group @to-list]
           ^{:key (:date group)}
           [:div
            [:div
             (if (= group @group-edit)
               [initial-focus-wrapper
                [:input {:type      "text"
                         :class     "form-control"
                         :value     @label
                         :on-change #(dispatch-sync [:group-label-set (-> % .-target .-value)])
                         :on-blur   #(do
                                      (dispatch [:group-update group (assoc group :name @label)])
                                      (dispatch [:group-edit-set nil]))
                         }]]
               [:h3 {:on-click #(dispatch [:group-edit-set group])} (group-label group)]
               )
             [:small [:a {:on-click #(dispatch [:group-delete-set group])} "Delete"]]
             ]

            [:table {:class "table table-striped table-hover"}
             [:thead
              [:tr
               [:th "#"]
               [:th "Title"]
               [:th "URL"]]]
             [:tbody
386
              (list-tabs (filter-tabs (:tabs group)) true)]
387
             ]]))
388 389 390 391
       ]
      )
    ))

Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
392

Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
(defn data-export []
  (let [data      (subscribe [:data])
        as-string (reaction (.stringify js/JSON (clj->js (dissoc @data :tabs)) nil 2))]
    (fn []
      [:div
       [:div {:class "page-header"} [:h2 "Current data"]]
       [:p (str "Copy the JSON below to a safe location. Size: " (count @as-string))]
       [:textarea {:class     "form-control"
                   :rows      30
                   :read-only true
                   ;; We will not export the current tab list
                   :value     @as-string}
        ]
       ])))

Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
(defn data-import []
  (let [path        [:app-state :import]
        import-data (subscribe path)]
    (fn []
      [:div
       [:div {:class "page-header"} [:h2 "Import data"]]
       [:div {:class "alert alert-warning"}
        [:h4 "Warning!"]
        [:p "Any data item for which there is a key on the JSON below be replaced!"]]
       [:textarea {:class     "form-control"
                   :rows      30
                   :value     @import-data
                   :on-change #(dispatch [:app-state-item path (-> % .-target .-value)])}]
       [:a {:class    "btn btn-danger btn-sm"
            :on-click #(dispatch [:data-import @import-data])} "Import"]
       ])))

425

426
(def component-dir {:monitor current-tabs
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
427
                    :groups  tab-groups
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
428 429
                    :export  data-export
                    :import  data-import})
430 431 432 433 434 435 436 437 438 439


(defn main-section []
  (let [section   (subscribe [:ui-state :section])
        component (reaction (get component-dir @section))]
    (fn []
      (if (some? @component)
        [@component]
        [:div "Work in progress..."]))))

440 441 442 443 444 445 446 447
;;;;----------------------------
;;;; Chrome subscriptions
;;;;----------------------------

(defn dispatch-on-channel
  "Dispatched msg when there's content received on the channel returned by
  function chan-f."
  [msg chan-f]
448 449 450 451 452
  (let [channel (chan-f)]
    (go (while true
          (let [content (<! channel)]
            (dispatch [msg content]))))
    ))
453 454 455


(defn mount-components []
456 457
  (reagent/render-component [navbar] (.getElementById js/document "navbar"))
  (reagent/render-component [main-section] (.getElementById js/document "main-section")))
458 459 460


(defn init []
Ricardo J. Mendez's avatar
Ricardo J. Mendez committed
461
  (console/log "Initialized booklet.core")
462 463 464 465
  (go (let [window (<! (windows/get-current))
            state  (<! (idle/query-state 30))]
        (dispatch-sync [:initialize (:tabs window)])
        (dispatch-sync [:idle-state-change {:newState state}])))
466
  (let [bg (runtime/connect)]
467
    (dispatch-on-channel :log-content storage/on-changed)
468 469 470 471
    (dispatch-on-channel :tab-created tabs/on-created)
    (dispatch-on-channel :tab-removed tabs/on-removed)
    (dispatch-on-channel :tab-updated tabs/on-updated)
    (dispatch-on-channel :tab-replaced tabs/on-replaced)
472 473
    (idle/set-detection-interval 60)
    (dispatch-on-channel :idle-state-change idle/on-state-changed)
474 475 476
    (go (>! bg :lol-i-am-a-popup)
        (console/log "Background said: " (<! bg))))
  (mount-components))