;; This Source Code Form is subject to the terms of the Mozilla Public ;; License, v. 2.0. If a copy of the MPL was not distributed with this ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; ;; Copyright (c) UXBOX Labs S.L (ns app.main.ui.hooks "A collection of general purpose react hooks." (:require [app.common.files.focus :as cpf] [app.common.math :as mth] [app.main.broadcast :as mbc] [app.main.data.shortcuts :as dsc] [app.main.refs :as refs] [app.main.store :as st] [app.util.dom :as dom] [app.util.dom.dnd :as dnd] [app.util.keyboard :as kbd] [app.util.storage :as storage] [app.util.timers :as ts] [app.util.webapi :as wapi] [beicon.v2.core :as rx] [beicon.v2.operators :as rxo] [goog.functions :as f] [rumext.v2 :as mf])) (def ^:private render-id 0) (defn use-render-id "Get a stable, DOM usable identifier across all react rerenders" [] (mf/useMemo #(js* "\"render-\" + (++~{})" render-id) #js [])) (defn use-rxsub [ob] (let [[state reset-state!] (mf/useState #(if (satisfies? IDeref ob) @ob nil))] (mf/useEffect (fn [] (let [sub (rx/sub! ob #(reset-state! %))] #(rx/dispose! sub))) #js [ob]) state)) (defn use-shortcuts [key shortcuts group-key] (mf/use-effect #js [(str key) shortcuts] (fn [] (st/emit! (dsc/push-shortcuts key shortcuts group-key)) (fn [] (st/emit! (dsc/pop-shortcuts key)))))) (defn- set-timer [state ms func] (assoc state :timer (ts/schedule ms func))) (defn- cancel-timer [state] (let [timer (:timer state)] (if timer (do (rx/dispose! timer) (dissoc state :timer)) state))) (def sortable-ctx (mf/create-context nil)) (mf/defc sortable-container* [{:keys [children]}] (let [global-drag-end (mf/use-memo #(rx/subject))] [:> (mf/provider sortable-ctx) {:value global-drag-end} children])) ;; The dnd API is problematic for nested elements, such a sortable items tree. ;; The approach used here to solve bad situations is: ;; - Capture all events in the leaf draggable elements, and stop propagation. ;; - Ignore events originated in non-draggable children. ;; - At drag operation end, all elements that have received some enter/over ;; event and have not received the corresponding leave event, are notified ;; so they can clean up. This can be occur, for example, if ;; * some leave events are throttled out because of a slow computer ;; * some corner cases of mouse entering a container element, and then ;; moving into a contained element. This is anyway mitigated by not ;; stopping propagation of leave event. ;; ;; Do not remove commented out lines, they are useful to debug events when ;; things go weird. ;; Native drag and drop swallows wheel events while a drag is in progress, so ;; scrolling a long list mid-drag is done here: when the pointer gets near the ;; top or bottom edge of the scrollable container, it is scrolled on every ;; animation frame, faster the closer the pointer is to the edge. (def ^:private auto-scroll-zone-size 56) (def ^:private auto-scroll-max-speed 18) (def ^:private auto-scroll-stale-ms 500) ;; Speeds are given in pixels per frame at 60 Hz and scaled by the real time ;; between frames, so the scroll goes as fast on a 120 Hz screen. (def ^:private auto-scroll-frame-ms (/ 1000 60)) (def ^:private auto-scroll-max-frame-ms 100) ;; State of the current drag: the scroll container, found once when the drag ;; starts, the scroll speed, the pending animation frame and when the pointer ;; was last seen over the list. (defonce ^:private auto-scroll-state (atom nil)) (defn- scrollable-ancestor [node] (loop [node (some-> ^js node .-parentElement)] (when (some? node) (let [overflow (-> (dom/get-computed-styles node) (dom/get-property-value "overflow-y"))] (if (and (or (= overflow "auto") (= overflow "scroll")) (> (.-scrollHeight ^js node) (.-clientHeight ^js node))) node (recur (.-parentElement ^js node))))))) (defn- auto-scroll-speed "Pixels to scroll on each frame given the pointer position, negative upwards. Zero when the pointer is outside the edge zones. The zones take at most a quarter of the container each, so the middle half of a short list never scrolls." [{:keys [top bottom]} pointer-y] (let [zone (mth/min auto-scroll-zone-size (/ (- bottom top) 4)) top-distance (- pointer-y top) bottom-distance (- bottom pointer-y) ramp (fn [distance] (-> (- zone distance) (/ zone) (* auto-scroll-max-speed) (mth/ceil)))] (cond (or (neg? top-distance) (neg? bottom-distance)) 0 (< top-distance zone) (- (ramp top-distance)) (< bottom-distance zone) (ramp bottom-distance) :else 0))) (defn- stop-auto-scroll! "Stops the scroll loop, keeping the scroll container for the rest of the drag." [] (some-> (:frame @auto-scroll-state) ts/cancel-af!) (swap! auto-scroll-state dissoc :frame :last-frame-at :offset)) (defn- end-auto-scroll! [] (stop-auto-scroll!) (reset! auto-scroll-state nil)) (defn- start-auto-scroll! "Remembers the scroll container of the dragged `node`. A loop left over from a previous drag whose end was lost is stopped first." [node] (stop-auto-scroll!) (reset! auto-scroll-state {:element (scrollable-ancestor node)})) (defn- auto-scroll-tick [timestamp] (let [{:keys [element speed updated-at last-frame-at offset]} @auto-scroll-state] ;; The stale check stops the loop if the drag ended without us being ;; notified, for example when a dragend event is lost. (if (or (nil? element) (> (- timestamp updated-at) auto-scroll-stale-ms)) (end-auto-scroll!) (let [;; Capped so a late frame does not make the list jump. elapsed (if (some? last-frame-at) (mth/min (- timestamp last-frame-at) auto-scroll-max-frame-ms) auto-scroll-frame-ms) ;; Keep the fraction of a pixel for the next frame, otherwise ;; slow speeds would be lost on fast screens. offset (+ (or offset 0) (* speed (/ elapsed auto-scroll-frame-ms))) step (js/Math.trunc offset)] (when-not (zero? step) (dom/scroll-by! element 0 step)) (swap! auto-scroll-state assoc :offset (- offset step) :last-frame-at timestamp :frame (ts/raf auto-scroll-tick)))))) (defn- update-auto-scroll! "Starts, updates or stops the auto scroll of the container of `node` depending on how close the pointer is to its edges." [node pointer-y] (let [element (:element @auto-scroll-state) ;; The drag may have started outside this list, or the loop ended ;; on the stale check: find the container of `node` again. element (if (dom/child? node element) element (scrollable-ancestor node)) speed (if (some? element) (auto-scroll-speed (dom/get-bounding-rect element) pointer-y) 0)] (swap! auto-scroll-state assoc :element element :speed speed :updated-at (js/performance.now)) (cond (zero? speed) (stop-auto-scroll!) (nil? (:frame @auto-scroll-state)) (swap! auto-scroll-state assoc :frame (ts/raf auto-scroll-tick))))) (defn use-sortable [& {:keys [data-type data on-drop on-drag on-hold disabled detect-center? draggable?] :or {draggable? true} :as opts}] (let [ref (mf/use-ref) state (mf/use-state {:over nil :timer nil :subscr nil}) global-drag-end (mf/use-ctx sortable-ctx) cleanup (fn [] (some-> (:subscr @state) rx/dispose!) (swap! state (fn [state] (-> state (cancel-timer) (dissoc :over :subscr))))) subscribe-to-drag-end (fn [] (when (nil? (:subscr @state)) (swap! state #(assoc % :subscr (rx/sub! global-drag-end cleanup))))) on-drag-start (fn [event] (if (or disabled (not draggable?)) (do (dom/stop-propagation event) (dom/prevent-default event)) (do (dom/stop-propagation event) (dnd/set-data! event data-type data) (dnd/set-drag-image! event (dnd/invisible-image)) (dnd/set-allowed-effect! event "move") (start-auto-scroll! (mf/ref-val ref)) (when (fn? on-drag) (on-drag data))))) on-drag-enter (fn [event] (dom/prevent-default event) ;; prevent default to allow drag enter (when-not (dnd/from-child? event) (dom/stop-propagation event) (subscribe-to-drag-end) ;; (dnd/trace event data "drag-enter") (when (fn? on-hold) (swap! state (fn [state] (-> state (cancel-timer) (set-timer 1000 on-hold))))))) on-drag-over (fn [event] (when (dnd/has-type? event data-type) (dom/prevent-default event) ;; prevent default to allow drag over (when-not (dnd/from-child? event) (dom/stop-propagation event) (subscribe-to-drag-end) ;; (dnd/trace event data "drag-over") (let [side (dnd/drop-side event detect-center?)] (swap! state assoc :over side))) (update-auto-scroll! (mf/ref-val ref) (.-clientY event)))) on-drag-leave (fn [event] (when-not (dnd/from-child? event) ;; (dnd/trace event data "drag-leave") (cleanup))) on-drop' (fn [event] (dom/stop-propagation event) ;; (dnd/trace event data "drop") (let [side (dnd/drop-side event detect-center?) drop-data (dnd/get-data event data-type)] (end-auto-scroll!) (cleanup) (rx/push! global-drag-end nil) (when (fn? on-drop) (on-drop side drop-data event)))) on-drag-end (fn [event] (dom/stop-propagation event) ;; (dnd/trace event data "drag-end") (end-auto-scroll!) (rx/push! global-drag-end nil) (cleanup)) on-mount (fn [] (let [dom (mf/ref-val ref)] ;; In firefox it needs to be draggable for problems with event handling. ;; It will stop the drag operation in on-drag-start (.setAttribute dom "draggable" (and draggable? (not disabled))) ;; Register all events in the (default) bubble mode, so that they ;; are captured by the most leaf item. The handler will stop ;; propagation, so they will not go up in the containment tree. (.addEventListener dom "dragstart" on-drag-start false) (.addEventListener dom "dragenter" on-drag-enter false) (.addEventListener dom "dragover" on-drag-over false) (.addEventListener dom "dragleave" on-drag-leave false) (.addEventListener dom "drop" on-drop' false) (.addEventListener dom "dragend" on-drag-end false) #(do (.removeEventListener dom "dragstart" on-drag-start) (.removeEventListener dom "dragenter" on-drag-enter) (.removeEventListener dom "dragover" on-drag-over) (.removeEventListener dom "dragleave" on-drag-leave) (.removeEventListener dom "drop" on-drop') (.removeEventListener dom "dragend" on-drag-end))))] (mf/use-effect (mf/deps data on-drop draggable?) on-mount) [(deref state) ref])) (defn use-stream "Wraps the subscription to a stream into a `use-effect` call" ([stream on-subscribe] (use-stream stream (mf/deps) on-subscribe)) ([stream deps on-subscribe] (use-stream stream deps on-subscribe nil)) ([stream deps on-subscribe on-dispose] (mf/use-effect deps (fn [] (when stream (let [sub (->> stream (rx/subs! on-subscribe))] #(do (rx/dispose! sub) (when on-dispose (on-dispose))))))))) ;; https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state ;; FIXME: replace with rumext (defn use-previous "Returns the value from previous render cycle." [value] (let [ref (mf/use-ref value)] (mf/use-effect (mf/deps value) (fn [] (mf/set-ref-val! ref value))) (mf/ref-val ref))) (defn use-update-var "Returns a var pointer what automatically updates with latest values." [value] (let [ptr (mf/use-var value)] (mf/with-effect [value] (reset! ptr value)) ptr)) ;; FIXME: replace with rumext (defn use-update-ref [value] (let [ref (mf/use-ref value)] (mf/with-effect [value] (mf/set-ref-val! ref value)) ref)) ;; FIXME: replace with rumext (defn use-ref-callback "Returns a stable callback pointer what calls the interned callback. The interned callback will be automatically updated on each render if the reference changes and works as noop if the pointer references to nil value." [f] (let [ptr (mf/use-ref nil)] (mf/with-effect [f] (mf/set-ref-val! ptr #js {:f f})) (mf/use-fn (fn [& args] (let [obj (mf/ref-val ptr)] (when ^boolean obj (apply (.-f obj) args))))))) ;; FIXME: replace with rumext (defn use-ref-value "Returns a ref that will be automatically updated when the value is changed" [v] (let [ref (mf/use-ref v)] (mf/with-effect [v] (mf/set-ref-val! ref v)) ref)) ;; FIXME: replace with rumext (defn use-equal-memo [val] (let [ref (mf/use-ref nil)] (when-not (= (mf/ref-val ref) val) (mf/set-ref-val! ref val)) (mf/ref-val ref))) ;; FIXME: replace with rumext (defn use-focus-timer-ref "Returns a ref for scheduling focus timers and disposes any pending timer on component unmount." [] (let [ref (mf/use-ref nil)] (mf/with-effect [] #(some-> (mf/ref-val ref) ts/dispose!)) ref)) ;; FIXME: rename to use-focus-objects (defn with-focus-objects ([objects] (let [focus (mf/deref refs/workspace-focus-selected)] (with-focus-objects objects focus))) ([objects focus] (mf/with-memo [focus objects] (cpf/focus-objects objects focus)))) ;; FIXME: replace with rumext (defn use-debounce [ms value] (let [[state update-state-fn] (mf/useState value) update-fn (mf/use-memo (mf/deps ms) #(f/debounce update-state-fn ms))] (mf/with-effect [value] (update-fn value)) state)) (defn use-throttle "Like `use-debounce`, but updates at most once per `ms` instead of only after the value stops changing: the first and the last value of each burst are both applied, so it stays live during continuous updates (e.g. a drag)." [ms value] (let [[state update-state-fn] (mf/useState value) update-fn (mf/use-memo (mf/deps ms) #(f/throttle update-state-fn ms))] (mf/with-effect [value] (update-fn value)) state)) (defn use-shared-state "A specialized hook that adds persistence and inter-context reactivity to the default mf/use-state hook. The state is automatically persisted under the provided key on localStorage. And it will keep watching events with type equals to `key` for new values." [key default] (let [id (mf/use-id) state* (mf/use-state #(get storage/user key default)) state (deref state*) stream (mf/with-memo [id] (->> mbc/stream (rx/filter #(not= (:id %) id)) (rx/filter #(= (:type %) key)) (rx/map deref)))] (mf/with-effect [state key id] (mbc/emit! id key state) (swap! storage/user assoc key state)) (use-stream stream (partial reset! state*)) state*)) (defn use-persisted-state "A specialized hook that adds persistence to the default mf/use-state hook. The state is automatically persisted under the provided key on localStorage. And it will keep watching events with type equals to `key` for new values." [key default] (let [id (mf/use-id) state* (mf/use-state #(get storage/user key default)) state (deref state*)] (mf/with-effect [state key id] (swap! storage/user assoc key state)) state*)) (defonce ^:private intersection-subject (rx/subject)) (defonce ^:private intersection-observer (delay (js/IntersectionObserver. (fn [entries _] (run! (partial rx/push! intersection-subject) (seq entries))) #js {:rootMargin "0px" :threshold #js [0 1.0]}))) (defn use-visible [ref & {:keys [once?]}] (let [state (mf/useState false) update-state! (aget state 1) state (aget state 0)] (mf/with-effect [once?] (let [node (mf/ref-val ref) stream (->> intersection-subject (rx/filter (fn [entry] (let [target (unchecked-get entry "target")] (identical? target node)))) (rx/map (fn [entry] (let [ratio (unchecked-get entry "intersectionRatio") intersecting? (unchecked-get entry "isIntersecting") intersecting? (or ^boolean intersecting? ^boolean (> ratio 0.5))] (when (and (true? intersecting?) (true? once?)) (.unobserve ^js @intersection-observer node)) intersecting?))) (rx/pipe (rxo/distinct-contiguous))) subs (rx/sub! stream update-state!)] (.observe ^js @intersection-observer node) (fn [] (.unobserve ^js @intersection-observer node) (rx/dispose! subs)))) state)) (defn- get-or-create-portal-container "Returns the singleton container div for the given category, creating and appending it to document.body on first access." [category] (let [body (dom/get-body) id (str "portal-container-" category)] (or (dom/query body (str "#" id)) (let [container (dom/create-element "div")] (dom/set-attribute! container "id" id) (dom/append-child! body container) container)))) (defn use-portal-container "Returns a shared singleton container div for React portals, identified by a logical category. Available categories: :modal — modal dialogs :popup — popups, dropdowns, context menus :tooltip — tooltips :default — general portal use (default) All portals in the same category share one