From 29babcb300ddf94f66d24efed68191d4356c86ab Mon Sep 17 00:00:00 2001 From: SouthFox Date: Wed, 20 Sep 2023 17:00:09 +0800 Subject: [PATCH] [front/feat] basic history feature --- src/main/frontend/db.cljs | 15 ++++++++++++ src/main/frontend/events.cljs | 46 +++++++++++++++++++++++++++-------- 2 files changed, 51 insertions(+), 10 deletions(-) create mode 100644 src/main/frontend/db.cljs diff --git a/src/main/frontend/db.cljs b/src/main/frontend/db.cljs new file mode 100644 index 0000000..50b697d --- /dev/null +++ b/src/main/frontend/db.cljs @@ -0,0 +1,15 @@ +(ns frontend.db + (:require [cljs.reader] + [re-frame.core :refer [reg-cofx]])) + +(defn set-ls-history + [user] + (.setItem js/localStorage "history" (str user))) + +(reg-cofx + :local-store-history + (fn [cofx _] + (assoc cofx :local-store-history + (into (list) + (some->> (.getItem js/localStorage "history") + (cljs.reader/read-string)))))) diff --git a/src/main/frontend/events.cljs b/src/main/frontend/events.cljs index 8f12a89..f7596fa 100644 --- a/src/main/frontend/events.cljs +++ b/src/main/frontend/events.cljs @@ -1,7 +1,8 @@ (ns frontend.events - (:require [re-frame.core :refer [reg-event-db reg-event-fx]] + (:require [re-frame.core :refer [reg-event-db reg-event-fx inject-cofx path after trim-v]] [superstructor.re-frame.fetch-fx] - [clojure.string :as str])) + [clojure.string :as str] + [frontend.db :refer [set-ls-history]])) (if js/goog.DEBUG @@ -13,6 +14,10 @@ [& params] (str/join "/" (cons api-url params))) +(def set-history-interceptor [(path :history) + (after set-ls-history) + trim-v]) + (reg-event-fx :set-active-page (fn [{:keys [db]} [_ {:keys [new-match id query]}]] @@ -82,12 +87,32 @@ :db (-> db (assoc-in [:loading :question] true))})) -(reg-event-db +(reg-event-fx + :set-history + set-history-interceptor + (fn [{:keys [db]} history] + (let [history-item (first history) + update? (fn [x] + (and (= (:id x) (:id history-item)) + (= (:type x) (:type history-item))))] + {:db (as-> db $ + (remove update? $) + (conj $ history-item))}))) + +(reg-event-fx :get-question-success - (fn [db [_ {body :body}]] - (-> db - (assoc-in [:loading :question] false) - (assoc-in [:post] body)))) + (fn [{:keys [db]} [_ {body :body}]] + (let [id (get-in db [:current-route :path-params :id]) + type (get-in db [:current-route :data :name]) + title (get-in body [:question :title]) + detil (get-in body [:question :detail])] + {:db (-> db + (assoc-in [:loading :question] false) + (assoc-in [:post] body)) + :dispatch [:set-history {:id id + :type type + :title title + :detil detil}]}))) (reg-event-db :get-question-failure @@ -122,7 +147,8 @@ (update-in db-path into (:answers body)) (assoc-in [:post :paging] (:paging body)))))) -(reg-event-db +(reg-event-fx :initialize-db - (fn [_ _] - {:current-route nil})) + [(inject-cofx :local-store-history)] + (fn [{:keys [local-store-history]} _] + {:db (assoc {} :history local-store-history)}))