chat / client / src / sueta / app / lobby.cljs
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
;; ported-from: src/app/rooms.ts (the lobby half) — via app/rooms.cljs
;;
;; The lobby: pick one of the rooms this browser knows, rename one, forget one,
;; paste an invite link, or start a new room. It resolves with a room secret and
;; then gets out of the way; sueta.main awaits it.
;;
;; FIRST SCREEN ON REPLICANT (Phase 5a). What it replaces is worth naming,
;; because the shape below is the answer to it: a 146-line closure keyed off a
;; self-referential `volatile!` holding its own render function, which wiped
;; `overlay.innerHTML` on every interaction and then re-attached every listener
;; and re-appended the language picker — a third rendering strategy, distinct
;; from ui.cljs's two.
;;
;; THREE LAYERS, and the boundaries are the point:
;;
;;   `init` / `step`  the whole behaviour, pure. (state, event) -> [state',
;;                    effects]; effects are data. No DOM, no localStorage, no
;;                    timers, no clock.
;;   `view`           state -> hiccup, pure and TOTAL: everything it reads is
;;                    in the state it is handed. That is what makes
;;                    test/vectors/lobby-view.json a golden vector rather than
;;                    a screenshot — see `:now` below.
;;   `lobby`          the only impure part: it runs the effects, owns the
;;                    clock, and hands the render loop to sueta.app.view.
;;
;; `:now` IS IN THE STATE ON PURPOSE. "4 minutes ago" is a function of the
;; clock, and a view that calls `js/Date.now` itself cannot be pinned by a
;; fixture — the snapshot would change silently with the wall clock, which is
;; exactly the shape of gate this project has produced seven of. The clock is
;; read in ONE place (the dispatch, before `step`), which is no less accurate
;; than the code it replaces: that re-rendered only on interaction too.
;;
;; NO `esc`. Hiccup text becomes a DOM text node, so escaping is structural and
;; the copy of `esc` that used to live beside this code in app/rooms.cljs is
;; gone. Nothing here may assign `.-innerHTML` (test/source-hygiene.test.mjs).
(ns sueta.app.lobby
  (:require [ardegazu.id.bridge-client :refer (IdBridge)]
            [ardegazu.social.join :refer (home-chip)]
            [sueta.app.rooms :as rooms]
            [sueta.app.view :as view]
            [sueta.config :as config]
            [sueta.i18n :as i18n :refer (t)]
            [ardegazu.rooms.js :as j]))

(def ^:private ARM-MS
  "Two-tap forget: the first tap arms the button, a second within this window
   deletes, and otherwise it disarms itself."
  3500)

(def ^:private LINK-RE
  "Anchored on purpose: the secret must be the whole input or a #fragment. An
   unanchored 43-char run would \"join\" the middle of any pasted JWT or hash."
  #"(?:#|^)([A-Za-z0-9_-]{43})(?=$|[&?\s])")

;; ---- the pure core ---------------------------------------------------------

(defn normalize
  "The persisted room list — a JS array of {s, label, ts, lts?} — as the three
   fields the view actually shows. The one boundary where the storage
   representation stops mattering."
  [js-rooms]
  (mapv (fn [r] {:s (unchecked-get r "s")
                 :label (unchecked-get r "label")
                 :ts (unchecked-get r "ts")})
        (array-seq js-rooms)))

(defn init [js-rooms now]
  {:rooms (normalize js-rooms)
   :renaming nil                        ; secret of the row being renamed
   :armed nil                           ; secret of the armed forget button
   :join-bad? false
   :now now})

(defn- parse-secret [text]
  (second (re-find LINK-RE (.trim ^string text))))

(defn step
  "The lobby's entire behaviour. Pure."
  [state [op a b]]
  (case op
    :open [state [[:resolve a]]]

    :rename-start [(assoc state :renaming a) []]
    :rename-cancel [(assoc state :renaming nil) []]

    ;; Guarded against the double commit: Enter commits, and the blur that
    ;; follows when the input is removed a frame later arrives as a SECOND
    ;; commit. Only the row still being renamed may commit — otherwise an
    ;; Escape would be undone by its own blur, and an Enter would bump `lts`
    ;; twice for one rename.
    :rename-commit (if (not= a (:renaming state))
                     [state []]
                     (let [label (.trim ^string (if (some? b) b ""))]
                       [(assoc state :renaming nil)
                        (if (seq label)
                          [[:rename a label] [:reload]]
                          [])]))

    :forget-tap (if (= a (:armed state))
                  [(assoc state :armed nil) [[:forget a] [:reload]]]
                  [(assoc state :armed a) [[:disarm-after ARM-MS a]]])
    :disarm [(cond-> state (= a (:armed state)) (assoc :armed nil)) []]

    ;; PWA fix: invite links open the browser, not the installed app, so the
    ;; lobby accepts a pasted link (or a bare secret) and joins directly.
    :join (if-some [secret (parse-secret (if (some? a) a ""))]
            [(assoc state :join-bad? false) [[:touch secret] [:resolve secret]]]
            [(assoc state :join-bad? true) [[:clear-join]]])

    :create [state [[:create (.trim ^string (if (some? a) a ""))]]]

    :rooms-loaded [(assoc state :rooms (normalize a)) []]

    [state []]))

;; ---- the view --------------------------------------------------------------

(defn- fmt-ago [ts now]
  (let [m (js/Math.round (/ (- now ts) 60000))]
    (cond
      (< m 1) (t "ago.now")
      (< m 60) (t "ago.m" {"n" m})
      (< m (* 60 24)) (t "ago.h" {"n" (js/Math.round (/ m 60))})
      :else (t "ago.d" {"n" (js/Math.round (/ m 1440))}))))

(defn- rename-row [{:keys [s label]}]
  [:div.room-row {:replicant/key s}
   [:input.rename-in {:type "text"
                      :maxlength "40"
                      :value label
                      :enterkeyhint "done"
                      :on {:keydown [:rename-key s] :blur [:rename-blur s]}
                      ;; the caret belongs to whoever is about to type in it.
                      ;; DATA, not a closure: an inline `(fn …)` here prints as
                      ;; `#object[Function]` in the snapshot, which is the exact
                      ;; opacity replicant was chosen over reagent to avoid —
                      ;; and it would have been the first thing in this repo to
                      ;; put one back.
                      :replicant/on-mount [:focus-rename s]}]])

(defn- room-row [{:keys [s label ts]} armed now]
  (let [armed? (= s armed)]
    [:div.room-row {:replicant/key s}
     [:button.room-open {:on {:click [:open s]}}
      [:span.room-label label]
      [:span.room-ago (fmt-ago ts now)]]
     [:button.icon-btn.small {:title (t "lobby.rename.title")
                              :on {:click [:rename-start s]}}
      "✎"]
     [:button.icon-btn.small.forget {:class (when armed? "armed")
                                     :title (t "lobby.forget.title")
                                     :on {:click [:forget-tap s]}}
      (if armed? (t "lobby.forget.arm") "🗑")]]))

(defn view
  "state -> hiccup. Pure and total; pinned by test/vectors/lobby-view.json."
  [{:keys [rooms renaming armed join-bad? now]}]
  [:div.overlay.lobby
   [:div.modal.lobby-box
    [:h2 "sueta"]
    [:p (t "lobby.sub1") [:br] (t "lobby.sub2")]
    [:div.room-list
     (if (empty? rooms)
       [:p.hint (t "lobby.empty")]
       (for [r rooms]
         (if (= (:s r) renaming)
           (rename-row r)
           (room-row r armed now))))]
    [:form#new-room-form.new-room-form {:on {:submit [:create]}}
     [:input#new-room-name {:type "text"
                            :maxlength "40"
                            :placeholder (t "lobby.new.ph")
                            :enterkeyhint "go"
                            :autocomplete "off"}]
     [:button#new-room.primary {:type "submit"} (t "lobby.new")]]
    [:form#join-form.new-room-form {:on {:submit [:join]}}
     [:input#join-link {:type "text"
                        :placeholder (if join-bad? (t "lobby.bad-link") (t "lobby.join.ph"))
                        :enterkeyhint "go"
                        :autocomplete "off"
                        :spellcheck "false"}]
     [:button#join-room.primary.ghosty {:type "submit"} (t "lobby.join")]]
    [:p.hint (t "lobby.hint")]
    [:p.hint.ver (t "lobby.version" {"v" config/APP-VERSION})]
    ;; The language row is an imperatively built element with its own listeners
    ;; and its own subscription; replicant is given an empty slot and never
    ;; diffs its children, so the picker is built ONCE per lobby (the code this
    ;; replaces rebuilt it, and re-subscribed it, on every interaction).
    [:div.lang-slot {:replicant/on-mount [:mount-lang-picker]}]]])

;; ---- the runtime -----------------------------------------------------------

(defn- pick-lang!
  "Persist locally (set-lang, inside the picker), mirror to the suite identity
   record best-effort, then reload into the new language."
  [lang]
  (-> (js/Promise.resolve nil)
      (.then (fn [_]
               (let [bridge (IdBridge. (j/ordered "ns" config/NS
                                                  "bridgeUrl" config/ID-BRIDGE-URL))]
                 (when (j/truthy? (.mirrorSeed ^js bridge))
                   (.putProfile ^js bridge (j/ordered "lang" lang))))))
      (.catch (fn [_] nil))
      (.then (fn [_] (.reload js/location))))
  js/undefined)

(defn lobby
  "Full-screen lobby; resolves with the chosen or newly created room secret."
  [root make-secret]
  (js/Promise.
   (fn [resolve _reject]
     (let [host (js/document.createElement "div")
           state (atom (init (rooms/load-rooms) (js/Date.now)))
           ;; the mounted screen, or nil once it is over. nil BEFORE the first
           ;; paint too, which is what a mount hook firing mid-render sees —
           ;; and a render triggered from inside a render is exactly the
           ;; re-entrancy replicant defers with its own frame.
           ui (volatile! nil)
           fire! (volatile! nil)
           render! (fn [] (when-some [u @ui] ((:schedule! u))) js/undefined)
           value-of (fn [sel] (.-value ^js (.querySelector host sel)))
           done (fn [secret]
                  ;; the screen is over: nothing may paint into a detached host,
                  ;; including an animation frame that is already queued (a
                  ;; stray render re-runs the mount hooks and subscribes a
                  ;; second language picker to on-lang-change)
                  (when-some [u @ui] ((:unmount! u)))
                  (vreset! ui nil)
                  (.remove (.-classList js/document.body) "soc-menu")
                  (.remove host)
                  (resolve secret)
                  js/undefined)
           run! (fn run! [[fx a b]]
                  (case fx
                    :resolve (done a)
                    :touch (rooms/touch-room a)
                    :rename (rooms/rename-room a b)
                    :forget (rooms/forget-room a)
                    :reload (@fire! [:rooms-loaded (rooms/load-rooms)])
                    :disarm-after (js/setTimeout (fn [] (@fire! [:disarm b])) a)
                    ;; DOM state, not markup: the input is uncontrolled (the
                    ;; caret is the user's), so a rejected paste is cleared by
                    ;; hand rather than by re-rendering a value over it
                    :clear-join (set! (.-value ^js (.querySelector host "#join-link")) "")
                    :create (let [secret (make-secret)]
                              (rooms/touch-room secret)
                              (when (seq a) (rooms/rename-room secret a))
                              (done secret)))
                  js/undefined)]

       ;; the lobby is a menu screen: show the kit's "back to the hub" chip
       ;; (renders nothing until body.soc-menu; idempotent across lobby visits)
       (.add (.-classList js/document.body) "soc-menu")
       (try (home-chip (j/ordered "t" i18n/t-kit)) (catch :default _ nil))

       (vreset!
        fire!
        (fn fire! [event]
          (when (some? event)
            (let [[state' effects] (step (assoc @state :now (js/Date.now)) event)]
              (reset! state state')
              (doseq [effect effects] (run! effect))
              (render!)))
          js/undefined))

       (.appendChild ^js root host)
       (vreset!
        ui
        (view/mount!
         host
         (fn [] (view @state))
              ;; DOM events carry what only the DOM knows — which key, what the
              ;; user typed — and become plain events before `step` sees them.
              ;; The one data LIFE-CYCLE hook arrives here too, with a
              ;; :replicant/node and no :replicant/dom-event.
         (fn [replicant-data handler-data]
           (let [e (:replicant/dom-event replicant-data)]
             (@fire! (case (first handler-data)
                       :join (do (.preventDefault ^js e) [:join (value-of "#join-link")])
                       :create (do (.preventDefault ^js e) [:create (value-of "#new-room-name")])
                       :rename-blur [:rename-commit (second handler-data)
                                     (.-value (.-target ^js e))]
                       :rename-key (case (.-key ^js e)
                                     "Enter" [:rename-commit (second handler-data)
                                              (.-value (.-target ^js e))]
                                     "Escape" [:rename-cancel]
                                     nil)
                            ;; the two data LIFE-CYCLE hooks: both act on the
                            ;; node they are handed and produce no event
                       :focus-rename (let [node (:replicant/node replicant-data)]
                                       (.focus ^js node)
                                       (.select ^js node)
                                       nil)
                       :mount-lang-picker
                       (do (.appendChild ^js (:replicant/node replicant-data)
                                         (i18n/lang-picker-el {:on-pick pick-lang!}))
                           nil)
                       handler-data)))
           js/undefined)))))))

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/chat.git