penpot/frontend/src/app/main/ui/hooks.cljs
Filip Sajdak 576bf4ed3d
✨ Close search and shortcuts panels with Escape (#12374)
* ✨ Close search and shortcuts panels with Escape

The workspace search and shortcuts panels could only be dismissed with
the mouse, which interrupts keyboard-first workflows.

A new use-escape-to-close hook gives each panel an on-key-down handler
that closes it on Escape while the user is working in it: the latest
pointer press or focus change must have landed inside the panel, or the
panel must hold focus when it opens (a panel that autofocuses its search
box, such as Shortcuts, is closed by the first Escape). Focus left
behind in a panel after the user moved on to the canvas does not count,
so Escape keeps its usual meaning there.

The handler never stops the event. The global Escape shortcut still
runs and finishes in-progress operations such as path drawing; an
earlier version stopped propagation and left a half-drawn path that
failed shape validation on the next commit.

In the search panel an open filters menu takes the first Escape and
the panel closes on the second.

The history panel needs no handler: Escape already closes it through
the :interrupt it emits.

Closes #9540

AI-assisted-by: claude-opus-5-5
AI-assisted-by: claude-sonnet-5-5
Signed-off-by: Filip Sajdak <filip.sajdak@siili.com>

* 📎 Add e2e test for closing panels with Escape

Cover the Escape handling added for the layers search and shortcuts
panels with four Playwright cases on the mocked workspace:

- Escape closes the layers search panel.
- With the search filters menu open, the first Escape closes only the
  menu and the second closes the panel.
- Escape closes the shortcuts panel right after it opens with `?`. The
  panel autofocuses its search box, so the first Escape must close it
  instead of only blurring the box.
- A path drawn while focus sits in the shortcuts panel is finished by
  Escape, which proves the panel does not swallow the global shortcut.

The first three cases fail on develop. The shortcuts case also fails
when the hook does not seed its tracker from the focused element.

AI-assisted-by: claude-sonnet-5-5
Signed-off-by: Filip Sajdak <filip.sajdak@siili.com>

* 🐛 Close History with Escape when opened by shortcut or menu

Only the header button opened History through initialize-history, which
removes the :document-history flag on the next :interrupt. The
Ctrl/Cmd+Alt+H shortcut and the "Version history" menu item toggled the
flag directly, so the global Escape left the panel open. Both now emit
initialize-history, like the header, and keep their own event origin.

Two e2e cases cover the shortcut and the menu; both fail without this
change.

AI-assisted-by: claude-sonnet-5-5
Signed-off-by: Filip Sajdak <filip.sajdak@siili.com>

* ♻️ Apply review suggestions to Escape-to-close

Use dom/child? instead of .contains in the Escape hook and drop the
redundant nil checks. Drive the path test through clickAt so its clicks
wait for the path tool. Add a negative Search case: Escape reaches the
panel after the last click landed on the viewport, and the panel stays
open. That case fails when the containment check is removed.

AI-assisted-by: claude-sonnet-5-5
Signed-off-by: Filip Sajdak <filip.sajdak@siili.com>

---------

Signed-off-by: Filip Sajdak <filip.sajdak@siili.com>
2026-10-26 14:42:43 +01:00

642 lines
23 KiB
Clojure

;; 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 <div> on document.body,
keeping the DOM clean and avoiding removeChild race conditions."
([]
(use-portal-container :default))
([category]
(let [category (name category)]
(mf/with-memo [category]
(get-or-create-portal-container category)))))
(defn use-dynamic-grid-item-width
([] (use-dynamic-grid-item-width nil))
([itemsize]
(let [width* (mf/use-state nil)
width (deref width*)
rowref (mf/use-ref)
itemsize (cond
(some? itemsize) itemsize
(>= width 1030) 280
:else 230)
ratio (if (some? width) (/ width itemsize) 0)
nitems (mth/floor ratio)
limit (mth/min 10 nitems)
limit (mth/max 1 limit)
th-size (when width
(mth/floor (- (/ (- width 32 (* (dec limit) 24)) limit) 12)))
;; Need an even value
th-size (if (odd? (int th-size)) (- th-size 1) th-size)]
(mf/with-effect
[th-size]
(when th-size
(let [node (mf/ref-val rowref)]
(.setProperty (.-style node) "--thumbnail-width" (str th-size "px"))
(.setProperty (.-style node) "--thumbnail-height" (str (mth/ceil (* th-size (/ 2 3))) "px")))))
(mf/with-effect []
(let [node (mf/ref-val rowref)
mnt? (volatile! true)
sub (->> (wapi/observe-resize node)
(rx/subs! (fn [entries]
(let [row (first entries)
row-rect (.-contentRect ^js row)
row-width (.-width ^js row-rect)]
(when @mnt?
(reset! width* row-width))))))]
(fn []
(vreset! mnt? false)
(rx/dispose! sub))))
[rowref limit])))
(defn use-escape-to-close
"Returns an `on-key-down` handler that closes a panel with Escape.
The panel only closes while the user is working in it: the latest
pointer press or focus change must have landed inside the element
that owns the handler, or that element must hold focus when it
mounts. Focus left behind in a panel after the user moved on to the
canvas does not count, so Escape keeps its usual meaning there.
The event is never stopped: the global Escape shortcut still runs
and finishes any in-progress operation.
`dismiss-nested`, when given, is called first; it returns true when
it consumed the Escape (an open menu, an inline rename), and then
the panel stays open."
([on-close]
(use-escape-to-close on-close nil))
([on-close dismiss-nested]
(let [last-target-ref (mf/use-ref nil)]
(mf/with-effect []
(let [track (fn [event]
(mf/set-ref-val! last-target-ref (dom/get-target event)))]
;; A panel that autofocuses its input on open has already
;; received its `focusin` before this effect runs.
(mf/set-ref-val! last-target-ref (dom/get-active))
(.addEventListener js/document "pointerdown" track true)
(.addEventListener js/document "focusin" track true)
#(do (.removeEventListener js/document "pointerdown" track true)
(.removeEventListener js/document "focusin" track true))))
(mf/use-fn
(mf/deps on-close dismiss-nested)
(fn [event]
(let [panel (dom/get-current-target event)
last-target (mf/ref-val last-target-ref)]
(when (and (kbd/esc? event)
(dom/child? last-target panel)
(not (and (fn? dismiss-nested) (dismiss-nested))))
(dom/blur! (dom/get-target event))
(on-close))))))))