feat: add TodoMVC example with editorial design
Full TodoMVC implementation using Pocketbook's synced atom: - Add, toggle, edit (double-click), destroy todos - Filter: All / Active / Completed - Toggle all, clear completed - Live sync status indicator (online/offline/pending) - Data persists in IndexedDB, syncs to server via Transit Design: Ink & Paper aesthetic — cream paper background with grain texture, Instrument Serif italic header, Newsreader body text, DM Mono UI chrome, terracotta accent with green completion marks, deckled left border on card. Also: - Server now serves static files from resources/public (/ → todomvc.html) - Fix CLJS compilation: resolve close!/put! naming conflicts with core.async, use qualified async/close!, add clojure.string require - Fix unbalanced parens in do-pull! - Remove old placeholder example
This commit is contained in:
@@ -11,7 +11,8 @@
|
||||
"
|
||||
(:require [pocketbook.idb :as idb]
|
||||
[pocketbook.sync :as sync]
|
||||
[cljs.core.async :refer [go go-loop <! >! chan put! close! timeout alts!]]))
|
||||
[clojure.string :as str]
|
||||
[cljs.core.async :as async :refer [go go-loop <! >! chan put! timeout alts!]]))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Connection (IDB handle)
|
||||
@@ -25,17 +26,17 @@
|
||||
(go
|
||||
(let [db (<! (idb/open db-name))]
|
||||
(>! ch {:db db :db-name db-name})
|
||||
(close! ch)))
|
||||
(async/close! ch)))
|
||||
ch))
|
||||
|
||||
(defn close!
|
||||
(defn shutdown!
|
||||
"Close a Pocketbook connection."
|
||||
[{:keys [db atoms]}]
|
||||
;; Stop all sync loops
|
||||
(doseq [[_ sa] @(or atoms (atom {}))]
|
||||
(when-let [stop (:stop-fn sa)]
|
||||
(stop)))
|
||||
(idb/close! db))
|
||||
(idb/close-db! db))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Synced Atom — implements IAtom semantics
|
||||
@@ -122,7 +123,7 @@
|
||||
(.now js/Date))
|
||||
|
||||
(defn- doc-in-group? [group id]
|
||||
(clojure.string/starts-with? id (prefix-str group)))
|
||||
(str/starts-with? id (prefix-str group)))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; IDB ↔ Atom sync
|
||||
@@ -151,7 +152,7 @@
|
||||
(str "last-sync:" (.-group sa))))]
|
||||
(reset! (.-last_sync sa) (or ls 0)))
|
||||
(put! ch true)
|
||||
(close! ch)))
|
||||
(async/close! ch)))
|
||||
ch))
|
||||
|
||||
(defn- write-doc-to-idb!
|
||||
@@ -188,12 +189,12 @@
|
||||
[sa]
|
||||
(go
|
||||
(when-let [opts (.-server_opts sa)]
|
||||
(let [since @(.-last_sync sa)
|
||||
(let [since @(.-last_sync sa)
|
||||
result (<! (sync/pull! opts (.-group sa) since))]
|
||||
(when (:ok result)
|
||||
(let [docs (:docs result)
|
||||
max-ts (reduce max @(.-last_sync sa)
|
||||
(map :updated docs))]
|
||||
(let [docs (:docs result)
|
||||
max-ts (reduce max @(.-last_sync sa)
|
||||
(map :updated docs))]
|
||||
;; Merge each doc into cache
|
||||
(doseq [doc docs]
|
||||
(let [id (:id doc)]
|
||||
@@ -215,7 +216,7 @@
|
||||
;; Update last-sync
|
||||
(reset! (.-last_sync sa) max-ts)
|
||||
(idb/set-meta! (:db (.-conn sa))
|
||||
(str "last-sync:" (.-group sa)) max-ts)))
|
||||
(str "last-sync:" (.-group sa)) max-ts))
|
||||
true)))))
|
||||
|
||||
(defn- do-push!
|
||||
@@ -325,7 +326,7 @@
|
||||
(go
|
||||
(<! (load-from-idb! sa))
|
||||
(put! ready-ch true)
|
||||
(close! ready-ch)
|
||||
(async/close! ready-ch)
|
||||
;; Initial sync
|
||||
(when server-opts
|
||||
(<! (do-sync! sa))
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
(ns pocketbook.example
|
||||
"Example: a simple todo app using Pocketbook."
|
||||
(:require [pocketbook.core :as pb]
|
||||
[cljs.core.async :refer [go <!]]))
|
||||
|
||||
(defn- render-todos! [todos-atom]
|
||||
(let [todos @todos-atom
|
||||
container (js/document.getElementById "app")]
|
||||
(set! (.-innerHTML container)
|
||||
(str "<h1>Pocketbook Todos (" (count todos) ")</h1>"
|
||||
"<div id='add-form'>"
|
||||
"<input id='new-todo' type='text' placeholder='New todo...' />"
|
||||
"<button id='add-btn'>Add</button>"
|
||||
"</div>"
|
||||
"<ul>"
|
||||
(apply str
|
||||
(for [[id doc] (sort-by key todos)]
|
||||
(str "<li>"
|
||||
"<label>"
|
||||
"<input type='checkbox' data-id='" id "' "
|
||||
(when (:done doc) "checked") " /> "
|
||||
"<span" (when (:done doc) " style='text-decoration:line-through'") ">"
|
||||
(:text doc)
|
||||
"</span>"
|
||||
"</label>"
|
||||
" <button class='del-btn' data-id='" id "'>✕</button>"
|
||||
"</li>")))
|
||||
"</ul>"
|
||||
"<p style='color:#888;font-size:12px'>"
|
||||
"Pending sync: " (pb/pending-count todos-atom)
|
||||
"</p>"))))
|
||||
|
||||
(defn- setup-handlers! [todos-atom]
|
||||
;; We re-setup after each render
|
||||
(when-let [btn (js/document.getElementById "add-btn")]
|
||||
(.addEventListener btn "click"
|
||||
(fn [_]
|
||||
(let [input (js/document.getElementById "new-todo")
|
||||
text (.-value input)]
|
||||
(when (seq text)
|
||||
(let [id (str "todo:" (random-uuid))]
|
||||
(swap! todos-atom assoc id {:text text :done false})
|
||||
(set! (.-value input) "")))))))
|
||||
;; Checkbox toggles
|
||||
(doseq [cb (array-seq (.querySelectorAll js/document "input[type=checkbox]"))]
|
||||
(.addEventListener cb "change"
|
||||
(fn [e]
|
||||
(let [id (.-id (.-dataset (.-target e)))]
|
||||
(swap! todos-atom update-in [id :done] not)))))
|
||||
;; Delete buttons
|
||||
(doseq [btn (array-seq (.querySelectorAll js/document ".del-btn"))]
|
||||
(.addEventListener btn "click"
|
||||
(fn [e]
|
||||
(let [id (.-id (.-dataset (.-target e)))]
|
||||
(swap! todos-atom dissoc id))))))
|
||||
|
||||
(defn ^:export init []
|
||||
(go
|
||||
(let [conn (<! (pb/open "pocketbook-example"))
|
||||
todos (pb/synced-atom conn "todo"
|
||||
{:server "http://localhost:8090/sync"})]
|
||||
;; Wait for initial load
|
||||
(<! (pb/ready? todos))
|
||||
;; Render
|
||||
(render-todos! todos)
|
||||
(setup-handlers! todos)
|
||||
;; Re-render on changes
|
||||
(add-watch todos :render
|
||||
(fn [_ _ _ _]
|
||||
(render-todos! todos)
|
||||
(setup-handlers! todos)))
|
||||
(js/console.log "Pocketbook example loaded!" (count @todos) "todos"))))
|
||||
|
||||
;; Auto-init
|
||||
(init)
|
||||
@@ -2,7 +2,7 @@
|
||||
"IndexedDB wrapper with Transit serialization.
|
||||
Stores documents as Transit-encoded strings preserving all Clojure types."
|
||||
(:require [cognitect.transit :as t]
|
||||
[cljs.core.async :refer [chan put! close!]]))
|
||||
[cljs.core.async :as async :refer [chan put!]]))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Transit
|
||||
@@ -40,11 +40,11 @@
|
||||
(set! (.-onsuccess req)
|
||||
(fn [e]
|
||||
(put! ch (.-result (.-target e)))
|
||||
(close! ch)))
|
||||
(async/close! ch)))
|
||||
(set! (.-onerror req)
|
||||
(fn [e]
|
||||
(js/console.error "IDB open error:" e)
|
||||
(close! ch)))
|
||||
(async/close! ch)))
|
||||
ch))
|
||||
|
||||
(defn- tx
|
||||
@@ -68,8 +68,8 @@
|
||||
:deleted (boolean (:deleted doc false))
|
||||
:synced (boolean (:synced doc false))}
|
||||
req (.put store obj)]
|
||||
(set! (.-onsuccess req) (fn [_] (put! ch true) (close! ch)))
|
||||
(set! (.-onerror req) (fn [e] (js/console.error "IDB put error:" e) (close! ch)))
|
||||
(set! (.-onsuccess req) (fn [_] (put! ch true) (async/close! ch)))
|
||||
(set! (.-onerror req) (fn [e] (js/console.error "IDB put error:" e) (async/close! ch)))
|
||||
ch))
|
||||
|
||||
(defn put-docs!
|
||||
@@ -86,8 +86,8 @@
|
||||
:deleted (boolean (:deleted doc false))
|
||||
:synced (boolean (:synced doc false))}]
|
||||
(.put store obj)))
|
||||
(set! (.-oncomplete txn) (fn [_] (put! ch true) (close! ch)))
|
||||
(set! (.-onerror txn) (fn [e] (js/console.error "IDB batch put error:" e) (close! ch)))
|
||||
(set! (.-oncomplete txn) (fn [_] (put! ch true) (async/close! ch)))
|
||||
(set! (.-onerror txn) (fn [e] (js/console.error "IDB batch put error:" e) (async/close! ch)))
|
||||
ch))
|
||||
|
||||
(defn get-doc
|
||||
@@ -107,9 +107,9 @@
|
||||
:updated (.-updated result)
|
||||
:deleted (.-deleted result)
|
||||
:synced (.-synced result)}))
|
||||
(close! ch))))
|
||||
(async/close! ch))))
|
||||
(set! (.-onerror req)
|
||||
(fn [e] (js/console.error "IDB get error:" e) (close! ch)))
|
||||
(fn [e] (js/console.error "IDB get error:" e) (async/close! ch)))
|
||||
ch))
|
||||
|
||||
(defn get-all-by-prefix
|
||||
@@ -137,9 +137,9 @@
|
||||
(.continue cursor))
|
||||
(do
|
||||
(put! ch @docs)
|
||||
(close! ch))))))
|
||||
(async/close! ch))))))
|
||||
(set! (.-onerror req)
|
||||
(fn [e] (js/console.error "IDB cursor error:" e) (close! ch)))
|
||||
(fn [e] (js/console.error "IDB cursor error:" e) (async/close! ch)))
|
||||
ch))
|
||||
|
||||
(defn get-unsynced
|
||||
@@ -166,9 +166,9 @@
|
||||
(.continue cursor))
|
||||
(do
|
||||
(put! ch @docs)
|
||||
(close! ch))))))
|
||||
(async/close! ch))))))
|
||||
(set! (.-onerror req)
|
||||
(fn [e] (js/console.error "IDB unsynced error:" e) (close! ch)))
|
||||
(fn [e] (js/console.error "IDB unsynced error:" e) (async/close! ch)))
|
||||
ch))
|
||||
|
||||
(defn delete-doc!
|
||||
@@ -178,8 +178,8 @@
|
||||
txn (tx db "docs" :readwrite)
|
||||
store (.objectStore txn "docs")
|
||||
req (.delete store id)]
|
||||
(set! (.-onsuccess req) (fn [_] (put! ch true) (close! ch)))
|
||||
(set! (.-onerror req) (fn [e] (js/console.error "IDB delete error:" e) (close! ch)))
|
||||
(set! (.-onsuccess req) (fn [_] (put! ch true) (async/close! ch)))
|
||||
(set! (.-onerror req) (fn [e] (js/console.error "IDB delete error:" e) (async/close! ch)))
|
||||
ch))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
@@ -197,8 +197,8 @@
|
||||
(fn [e]
|
||||
(let [result (.-result (.-target e))]
|
||||
(put! ch (when result (.-value result)))
|
||||
(close! ch))))
|
||||
(set! (.-onerror req) (fn [_] (close! ch)))
|
||||
(async/close! ch))))
|
||||
(set! (.-onerror req) (fn [_] (async/close! ch)))
|
||||
ch))
|
||||
|
||||
(defn set-meta!
|
||||
@@ -208,15 +208,15 @@
|
||||
txn (tx db "meta" :readwrite)
|
||||
store (.objectStore txn "meta")
|
||||
req (.put store #js {:key key :value value})]
|
||||
(set! (.-onsuccess req) (fn [_] (put! ch true) (close! ch)))
|
||||
(set! (.-onerror req) (fn [_] (close! ch)))
|
||||
(set! (.-onsuccess req) (fn [_] (put! ch true) (async/close! ch)))
|
||||
(set! (.-onerror req) (fn [_] (async/close! ch)))
|
||||
ch))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Close
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
(defn close!
|
||||
(defn close-db!
|
||||
"Close the IDB connection."
|
||||
[db]
|
||||
(when db (.close db)))
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
(:require [org.httpkit.server :as http]
|
||||
[pocketbook.db :as db]
|
||||
[pocketbook.transit :as t]
|
||||
[clojure.string :as str])
|
||||
[clojure.string :as str]
|
||||
[clojure.java.io :as io])
|
||||
(:gen-class))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
@@ -111,6 +112,43 @@
|
||||
:when k]
|
||||
[k (or v "")]))))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Static file serving
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
(def ^:private content-types
|
||||
{"html" "text/html; charset=utf-8"
|
||||
"css" "text/css; charset=utf-8"
|
||||
"js" "application/javascript; charset=utf-8"
|
||||
"json" "application/json"
|
||||
"svg" "image/svg+xml"
|
||||
"png" "image/png"
|
||||
"jpg" "image/jpeg"
|
||||
"ico" "image/x-icon"
|
||||
"woff2" "font/woff2"
|
||||
"woff" "font/woff"
|
||||
"map" "application/json"})
|
||||
|
||||
(defn- ext [path]
|
||||
(let [i (str/last-index-of path ".")]
|
||||
(when (and i (pos? i))
|
||||
(subs path (inc i)))))
|
||||
|
||||
(defn- serve-static
|
||||
"Attempt to serve a static file from resources/public. Returns response or nil."
|
||||
[uri]
|
||||
(let [path (str "public" (if (= "/" uri) "/todomvc.html" uri))
|
||||
resource (io/resource path)]
|
||||
(when resource
|
||||
{:status 200
|
||||
:headers {"Content-Type" (get content-types (ext path) "application/octet-stream")
|
||||
"Cache-Control" "no-cache"}
|
||||
:body (io/input-stream resource)})))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Ring handler
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
(defn make-handler
|
||||
"Create the Ring handler function."
|
||||
[ds config]
|
||||
@@ -121,12 +159,6 @@
|
||||
(= :options (:request-method req))
|
||||
{:status 204 :headers {} :body nil}
|
||||
|
||||
;; Health check
|
||||
(= "/" (:uri req))
|
||||
{:status 200
|
||||
:headers {"Content-Type" "text/plain"}
|
||||
:body "pocketbook ok"}
|
||||
|
||||
;; Sync endpoints
|
||||
(= "/sync" (:uri req))
|
||||
(let [user (authenticate config req)]
|
||||
@@ -137,10 +169,12 @@
|
||||
:post (handle-push ds user req)
|
||||
(transit-response 405 {:error "Method not allowed"}))))
|
||||
|
||||
;; Static files (including / → todomvc.html)
|
||||
:else
|
||||
{:status 404
|
||||
:headers {"Content-Type" "text/plain"}
|
||||
:body "Not found"})]
|
||||
(or (serve-static (:uri req))
|
||||
{:status 404
|
||||
:headers {"Content-Type" "text/plain"}
|
||||
:body "Not found"}))]
|
||||
(if (:cors config)
|
||||
(cors-headers resp)
|
||||
resp))))
|
||||
@@ -161,6 +195,7 @@
|
||||
(println (str "🔶 Pocketbook server running on http://localhost:" (:port config)))
|
||||
(println (str " Database: " (:db-path config)))
|
||||
(println (str " Auth: " (if (:users config) "enabled" "disabled")))
|
||||
(println (str " TodoMVC: http://localhost:" (:port config) "/todomvc.html"))
|
||||
{:stop server
|
||||
:ds ds
|
||||
:config config})))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
(ns pocketbook.sync
|
||||
"HTTP sync client — pull and push documents to/from the Pocketbook server."
|
||||
(:require [cognitect.transit :as t]
|
||||
[cljs.core.async :refer [chan put! close!]]))
|
||||
[cljs.core.async :as async :refer [chan put!]]))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Transit over HTTP
|
||||
@@ -41,10 +41,10 @@
|
||||
(put! ch {:ok false
|
||||
:status (.-status resp)
|
||||
:error text}))
|
||||
(close! ch))))))
|
||||
(async/close! ch))))))
|
||||
(.catch (fn [err]
|
||||
(put! ch {:ok false :status 0 :error (str err)})
|
||||
(close! ch))))
|
||||
(async/close! ch))))
|
||||
ch))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
@@ -58,15 +58,15 @@
|
||||
(let [ch (chan 1)
|
||||
url (str server "?group=" (js/encodeURIComponent group)
|
||||
"&since=" since)]
|
||||
(cljs.core.async/go
|
||||
(let [result (cljs.core.async/<! (fetch-transit
|
||||
(async/go
|
||||
(let [result (async/<! (fetch-transit
|
||||
{:url url
|
||||
:method "GET"
|
||||
:headers (when token {"Authorization" (str "Bearer " token)})}))]
|
||||
(if (:ok result)
|
||||
(put! ch {:ok true :docs (:body result)})
|
||||
(put! ch result))
|
||||
(close! ch)))
|
||||
(async/close! ch)))
|
||||
ch))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
@@ -79,8 +79,8 @@
|
||||
Returns a channel yielding {:ok true :results [...]} or {:ok false :error str}."
|
||||
[{:keys [server token]} docs]
|
||||
(let [ch (chan 1)]
|
||||
(cljs.core.async/go
|
||||
(let [result (cljs.core.async/<! (fetch-transit
|
||||
(async/go
|
||||
(let [result (async/<! (fetch-transit
|
||||
{:url server
|
||||
:method "POST"
|
||||
:body docs
|
||||
@@ -88,7 +88,7 @@
|
||||
(if (:ok result)
|
||||
(put! ch {:ok true :results (:body result)})
|
||||
(put! ch result))
|
||||
(close! ch)))
|
||||
(async/close! ch)))
|
||||
ch))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
264
src/pocketbook/todomvc.cljs
Normal file
264
src/pocketbook/todomvc.cljs
Normal file
@@ -0,0 +1,264 @@
|
||||
(ns pocketbook.todomvc
|
||||
"TodoMVC built on Pocketbook — offline-first, synced, Clojure-native."
|
||||
(:require [pocketbook.core :as pb]
|
||||
[cljs.core.async :refer [go <!]]
|
||||
[clojure.string :as str]))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; State
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
(defonce !conn (atom nil))
|
||||
(defonce !todos (atom nil)) ;; the SyncedAtom
|
||||
(defonce !filter (atom :all)) ;; :all | :active | :completed
|
||||
(defonce !editing (atom nil)) ;; id of todo being edited, or nil
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Helpers
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
(defn- todos-list
|
||||
"Return todos as sorted vec of [id doc] pairs."
|
||||
[]
|
||||
(->> @(!todos)
|
||||
(sort-by (fn [[_ doc]] (:created doc)))
|
||||
vec))
|
||||
|
||||
(defn- active-todos []
|
||||
(remove (fn [[_ doc]] (:completed doc)) (todos-list)))
|
||||
|
||||
(defn- completed-todos []
|
||||
(filter (fn [[_ doc]] (:completed doc)) (todos-list)))
|
||||
|
||||
(defn- visible-todos []
|
||||
(case @!filter
|
||||
:all (todos-list)
|
||||
:active (active-todos)
|
||||
:completed (completed-todos)))
|
||||
|
||||
(defn- all-completed? []
|
||||
(let [ts (todos-list)]
|
||||
(and (seq ts) (every? (fn [[_ doc]] (:completed doc)) ts))))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Actions
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
(defn- add-todo! [text]
|
||||
(let [text (str/trim text)]
|
||||
(when (seq text)
|
||||
(let [id (str "todo:" (random-uuid))]
|
||||
(swap! @!todos assoc id
|
||||
{:text text
|
||||
:completed false
|
||||
:created (.now js/Date)})))))
|
||||
|
||||
(defn- toggle-todo! [id]
|
||||
(swap! @!todos update-in [id :completed] not))
|
||||
|
||||
(defn- toggle-all! []
|
||||
(let [target (not (all-completed?))]
|
||||
(swap! @!todos
|
||||
(fn [m]
|
||||
(reduce-kv (fn [acc k v] (assoc acc k (assoc v :completed target)))
|
||||
{} m)))))
|
||||
|
||||
(defn- destroy-todo! [id]
|
||||
(swap! @!todos dissoc id))
|
||||
|
||||
(defn- edit-todo! [id new-text]
|
||||
(let [text (str/trim new-text)]
|
||||
(if (seq text)
|
||||
(swap! @!todos assoc-in [id :text] text)
|
||||
(destroy-todo! id))
|
||||
(reset! !editing nil)))
|
||||
|
||||
(defn- clear-completed! []
|
||||
(swap! @!todos
|
||||
(fn [m]
|
||||
(into {} (remove (fn [[_ v]] (:completed v))) m))))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Rendering
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
(defn- esc [s]
|
||||
(-> (str s)
|
||||
(str/replace "&" "&")
|
||||
(str/replace "<" "<")
|
||||
(str/replace ">" ">")
|
||||
(str/replace "\"" """)))
|
||||
|
||||
(defn- render-todo-item [[id doc]]
|
||||
(let [editing? (= id @!editing)
|
||||
classes (str (when (:completed doc) " completed")
|
||||
(when editing? " editing"))]
|
||||
(str "<li class=\"todo-item" classes "\" data-id=\"" (esc id) "\">"
|
||||
"<div class=\"view\">"
|
||||
"<button class=\"toggle\" data-action=\"toggle\" data-id=\"" (esc id) "\">"
|
||||
(if (:completed doc) "◉" "○")
|
||||
"</button>"
|
||||
"<label class=\"todo-label\" data-action=\"edit-start\" data-id=\"" (esc id) "\">"
|
||||
(esc (:text doc))
|
||||
"</label>"
|
||||
"<button class=\"destroy\" data-action=\"destroy\" data-id=\"" (esc id) "\">×</button>"
|
||||
"</div>"
|
||||
(when editing?
|
||||
(str "<input class=\"edit-input\" data-action=\"edit-input\" data-id=\"" (esc id) "\""
|
||||
" value=\"" (esc (:text doc)) "\" />"))
|
||||
"</li>")))
|
||||
|
||||
(defn- render-footer [active-count total-count]
|
||||
(let [current @!filter]
|
||||
(str "<footer class=\"app-footer\">"
|
||||
"<span class=\"todo-count\">"
|
||||
"<strong>" active-count "</strong> "
|
||||
(if (= 1 active-count) "item" "items") " left"
|
||||
"</span>"
|
||||
"<nav class=\"filters\">"
|
||||
"<button class=\"filter-btn" (when (= :all current) " selected") "\" data-action=\"filter\" data-filter=\"all\">All</button>"
|
||||
"<button class=\"filter-btn" (when (= :active current) " selected") "\" data-action=\"filter\" data-filter=\"active\">Active</button>"
|
||||
"<button class=\"filter-btn" (when (= :completed current) " selected") "\" data-action=\"filter\" data-filter=\"completed\">Completed</button>"
|
||||
"</nav>"
|
||||
(when (pos? (- total-count active-count))
|
||||
"<button class=\"clear-completed\" data-action=\"clear-completed\">Clear completed</button>")
|
||||
"</footer>")))
|
||||
|
||||
(defn- render-sync-status []
|
||||
(let [pending (when @!todos (pb/pending-count @!todos))
|
||||
online? (.-onLine js/navigator)]
|
||||
(str "<div class=\"sync-bar\">"
|
||||
"<span class=\"sync-dot " (if online? "online" "offline") "\"></span>"
|
||||
"<span class=\"sync-text\">"
|
||||
(cond
|
||||
(not online?) "Offline — changes saved locally"
|
||||
(and pending (pos? pending)) (str "Syncing " pending " change" (when (> pending 1) "s") "…")
|
||||
:else "Synced")
|
||||
"</span>"
|
||||
"</div>")))
|
||||
|
||||
(defn- render! []
|
||||
(let [container (js/document.getElementById "app")
|
||||
todos (visible-todos)
|
||||
total (count (todos-list))
|
||||
active (count (active-todos))]
|
||||
(when container
|
||||
(set! (.-innerHTML container)
|
||||
(str
|
||||
"<header class=\"app-header\">"
|
||||
"<h1>todos</h1>"
|
||||
"<div class=\"input-row\">"
|
||||
(when (pos? total)
|
||||
(str "<button class=\"toggle-all" (when (all-completed?) " checked") "\" data-action=\"toggle-all\">❯</button>"))
|
||||
"<input id=\"new-todo\" class=\"new-todo\" placeholder=\"What needs to be done?\" autofocus />"
|
||||
"</div>"
|
||||
"</header>"
|
||||
(when (pos? total)
|
||||
(str "<section class=\"main\">"
|
||||
"<ul class=\"todo-list\">"
|
||||
(apply str (map render-todo-item todos))
|
||||
"</ul>"
|
||||
"</section>"
|
||||
(render-footer active total)))
|
||||
(render-sync-status))))))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Event delegation
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
(defn- find-action
|
||||
"Walk up from target to find an element with data-action."
|
||||
[el]
|
||||
(loop [node el]
|
||||
(when (and node (not= node js/document.body))
|
||||
(if-let [action (.. node -dataset -action)]
|
||||
[action node]
|
||||
(recur (.-parentElement node))))))
|
||||
|
||||
(defn- handle-click [e]
|
||||
(when-let [[action el] (find-action (.-target e))]
|
||||
(let [id (.. el -dataset -id)]
|
||||
(case action
|
||||
"toggle" (toggle-todo! id)
|
||||
"destroy" (destroy-todo! id)
|
||||
"toggle-all" (toggle-all!)
|
||||
"clear-completed" (clear-completed!)
|
||||
"filter" (reset! !filter (keyword (.. el -dataset -filter)))
|
||||
nil))))
|
||||
|
||||
(defn- handle-dblclick [e]
|
||||
(when-let [[action el] (find-action (.-target e))]
|
||||
(when (= action "edit-start")
|
||||
(let [id (.. el -dataset -id)]
|
||||
(reset! !editing id)
|
||||
(render!)
|
||||
;; Focus the edit input after render
|
||||
(js/requestAnimationFrame
|
||||
(fn []
|
||||
(when-let [input (.querySelector js/document ".edit-input")]
|
||||
(.focus input)
|
||||
;; Move cursor to end
|
||||
(let [len (.-length (.-value input))]
|
||||
(.setSelectionRange input len len)))))))))
|
||||
|
||||
(defn- handle-keydown [e]
|
||||
(let [key (.-key e)]
|
||||
(cond
|
||||
;; Enter on new-todo input
|
||||
(and (= key "Enter") (= "new-todo" (.. e -target -id)))
|
||||
(let [input (.-target e)]
|
||||
(add-todo! (.-value input))
|
||||
(set! (.-value input) ""))
|
||||
|
||||
;; Enter on edit input
|
||||
(and (= key "Enter") (.. e -target -dataset -action)
|
||||
(= "edit-input" (.. e -target -dataset -action)))
|
||||
(let [el (.-target e)]
|
||||
(edit-todo! (.. el -dataset -id) (.-value el)))
|
||||
|
||||
;; Escape cancels edit
|
||||
(and (= key "Escape") @!editing)
|
||||
(do (reset! !editing nil)
|
||||
(render!)))))
|
||||
|
||||
(defn- handle-blur [e]
|
||||
(when (and @!editing
|
||||
(.. e -target -dataset -action)
|
||||
(= "edit-input" (.. e -target -dataset -action)))
|
||||
(let [el (.-target e)]
|
||||
(edit-todo! (.. el -dataset -id) (.-value el)))))
|
||||
|
||||
(defn- bind-events! []
|
||||
(let [app (js/document.getElementById "app")]
|
||||
(.addEventListener app "click" handle-click)
|
||||
(.addEventListener app "dblclick" handle-dblclick)
|
||||
(.addEventListener js/document "keydown" handle-keydown)
|
||||
(.addEventListener app "focusout" handle-blur true)))
|
||||
|
||||
;; ---------------------------------------------------------------------------
|
||||
;; Init
|
||||
;; ---------------------------------------------------------------------------
|
||||
|
||||
(defn ^:export init []
|
||||
(go
|
||||
(let [conn (<! (pb/open "pocketbook-todomvc"))
|
||||
todos (pb/synced-atom conn "todo"
|
||||
{:server "http://localhost:8090/sync"
|
||||
:interval 15000})]
|
||||
(reset! !conn conn)
|
||||
(reset! !todos todos)
|
||||
;; Wait for IDB load
|
||||
(<! (pb/ready? todos))
|
||||
;; Initial render
|
||||
(render!)
|
||||
(bind-events!)
|
||||
;; Re-render on any data change
|
||||
(add-watch todos :render (fn [_ _ _ _] (render!)))
|
||||
;; Re-render on filter change
|
||||
(add-watch !filter :render (fn [_ _ _ _] (render!)))
|
||||
;; Online/offline status updates
|
||||
(.addEventListener js/window "online" (fn [_] (render!)))
|
||||
(.addEventListener js/window "offline" (fn [_] (render!)))
|
||||
(js/console.log "🔶 Pocketbook TodoMVC loaded —" (count @todos) "todos"))))
|
||||
|
||||
(init)
|
||||
Reference in New Issue
Block a user