🐛 Fix auto-grow text sizes after sync and page open

On the WebGL renderer, a sync re-measure of copies shared a 40 ms
batch with user resizes of the main text. The batch skipped the
component sync when any request asked for that. So a resize of the
main (grow type, font size, paste, search and replace) often never
reached copies on other pages or in other files, and the viewer and
exports showed the old size.

A batch now skips the sync only when every request asks for it, the
same rule as :save-undo?. Such an edit costs one extra short sync
round. That round holds only skip requests, so it stops after one
pass.

A copy that the sync switched from fixed to auto-grow was never
re-measured, because the check read the grow type before the sync.
The check now reads the grow type that the change sets. A copy that
the sync makes fixed is not re-measured.

A sync started without an undo group (library update dialog, color
and typography sync) committed with a fresh group, and its re-measure
and layout pass took other ones. Ctrl+Z first undid only the
re-measure and left the copies in the old box. The sync now picks its
group when it runs: inside an undo transaction (color, typography and
asset deletes) it takes the transaction's, otherwise a fresh one. The
re-measure and layout pass share it, so one undo reverts the edit, the
sync and its follow-ups, and a failed save rolls them back together.

On the SVG renderer, opening a page resized a copy with no position
data even when its size had not drifted. Measured sizes round up, so
17.4 became 18. The measurement from that resize then landed on the
user's last undo entry. The heal now reports whether it resized, and
the check phase resizes only when the size drifted.

The SVG page-open check covered only texts with overridden content.
A copy loses its touched flags, so a label overridden inside a main
(a Button label in a Card main) was never checked in the main's
copies, and its heal skips the component sync. The check now covers
every auto-grow text inside a copy, as the WebGL check does. The
heal's reflow now skips the component sync too: without undo it
touched the main component on every page open.

A page-open check measured with a font that failed to load wrote the
fallback font size. It now writes no size then; a copy without
position data still gets it. The WebGL and SVG renderers can measure
a text differently; a gap over 1 px makes each page open by a user of
the other renderer write the size back. Two browsers on the SVG
renderer can do the same: a long auto-width line can differ by more
than 1 px, and an auto-height text can wrap a line differently. This is
a known limit, noted in the text-heal docstring.

The drift check moves to text-size-drifted? in
app.common.geom.shapes.text, and takes a tolerance. Both renderers use
it: 1 px for the SVG check and the WebGL page-open check, 0.1 px for
the WebGL font-load check. The WebGL check did not skip axes that fill
their layout parent, so those texts looked stale on every page open
and were resized for nothing. It now reads the stored width and height
and skips fill axes.

The sync docstring and a test message gave the wrong reason for
:skip-component-sync?. :ignore-touched stops the resize from marking
:geometry-group. :skip-component-sync? stops the re-measure commit from
starting another sync. "Remasure" is now "re-measure" in
identifiers, test names and comments. The sync docstring now states
that an auto-grow copy takes the main's size on each geometry sync,
also with overridden content, until the re-measure or the page-open
check corrects it. The sync's undo comment no longer says the layout
pass gets the sync's undo group: the layout buffer drops it, and the
pass joins the same undo entry through :stack-undo?.

Tests: heal undo tests cover mixed user and sync batches in both
orders, and undo for both renderers. A heal leaves the undo stack
unchanged, and undo reverts the user edit. A heal reflow skips the
component sync. Sync tests cover a copy that becomes auto-grow
(re-measured) and one that becomes fixed (not), and a sync with no
undo group that shares one with its re-measure, also inside an undo
transaction, with and without a group of the edit. Viewport tests cover
no resize without drift, a drifted copy that resizes and settles, the
check of every auto-grow text in a copy, and no size write from a
failed font. Component tests mount the SVG renderer: a drifted copy is
measured once to check and once to settle, with no undo step, and a
matching copy is measured once. Stale-selrect tests cover skipped fill
axes. The drift tests move to common-tests.geom-shapes-text-test, with
tolerance and grow-type cases.

Relates to #12721

AI-assisted-by: claude-opus-5-5
This commit is contained in:
Pablo Alba 2026-11-17 12:46:54 +01:00 committed by Pablo Alba
parent 2964e88a8c
commit ef0333eafe
15 changed files with 718 additions and 188 deletions

View File

@ -9,7 +9,23 @@
[app.common.data.macros :as dm]
[app.common.geom.rect :as grc]
[app.common.geom.shapes.common :as gco]
[app.common.geom.shapes.transforms :as gtr]))
[app.common.geom.shapes.transforms :as gtr]
[app.common.math :as mth]
[app.common.types.shape.layout :as ctl]))
(defn text-size-drifted?
"True when a measured auto-grow size is off the stored one by more than
`tolerance` on an axis that grows (width for :auto-width, height for both
auto-grow types). An axis that fills its layout parent takes its size
from the layout, so it never drifts. Other grow types never drift."
[{:keys [grow-type width height] :as shape} new-width new-height tolerance]
(boolean
(or (and (= :auto-width grow-type)
(not (ctl/fill-width? shape))
(not (mth/close? width new-width tolerance)))
(and (contains? #{:auto-width :auto-height} grow-type)
(not (ctl/fill-height? shape))
(not (mth/close? height new-height tolerance))))))
(defn position-data->rect
[{:keys [x y width height]}]

View File

@ -74,3 +74,41 @@
shape {:points shape-points}
pd [{:x 200 :y 200 :width 20 :height 10}]]
(t/is (false? (gte/overlaps-position-data? shape pd))))))
(t/deftest text-size-drifted-ignores-sub-pixel-gaps
(t/is (not (gte/text-size-drifted? {:grow-type :auto-width :width 100 :height 17} 100.5 17.5 1)))
(t/is (not (gte/text-size-drifted? {:grow-type :auto-height :width 100 :height 17} 100 17.5 1))))
(t/deftest text-size-drifted-checks-only-the-growing-axis
(t/is (not (gte/text-size-drifted? {:grow-type :auto-height :width 100 :height 17} 140 17 1))
"auto-height width comes from the box, not the text")
(t/is (gte/text-size-drifted? {:grow-type :auto-height :width 100 :height 17} 100 34 1))
(t/is (gte/text-size-drifted? {:grow-type :auto-width :width 44 :height 17} 67 17 1))
(t/is (gte/text-size-drifted? {:grow-type :auto-width :width 44 :height 17} 44 34 1)
"auto-width grows in height too"))
(t/deftest text-size-drifted-treats-exactly-the-tolerance-as-rounding
(t/is (not (gte/text-size-drifted? {:grow-type :auto-height :width 100 :height 17} 100 18 1))
"a 1px height gap is rounding at a 1px tolerance")
(t/is (not (gte/text-size-drifted? {:grow-type :auto-width :width 44 :height 17} 45 17 1))
"a 1px width gap is rounding at a 1px tolerance")
(t/is (gte/text-size-drifted? {:grow-type :auto-height :width 100 :height 17} 100 17.5 0.1)
"a finer tolerance catches a sub-pixel gap"))
(t/deftest text-size-drifted-ignores-an-axis-that-fills-its-parent
(t/is (not (gte/text-size-drifted? {:grow-type :auto-height :width 100 :height 40
:layout-item-v-sizing :fill}
100 17 1))
"a height set by the layout is not drift")
(t/is (not (gte/text-size-drifted? {:grow-type :auto-width :width 200 :height 17
:layout-item-h-sizing :fill}
44 17 1))
"a width set by the layout is not drift")
(t/is (gte/text-size-drifted? {:grow-type :auto-width :width 200 :height 17
:layout-item-h-sizing :fill}
44 34 1)
"the axis that does not fill is still checked"))
(t/deftest text-size-drifted-ignores-other-grow-types
(t/is (not (gte/text-size-drifted? {:grow-type :fixed :width 100 :height 17} 300 90 1)))
(t/is (not (gte/text-size-drifted? {:width 100 :height 17} 300 90 1))))

View File

@ -882,7 +882,7 @@
(t/deftest sync-text-override-with-geometry-touched-keeps-width
;; Documents the #12721 gap: text+geometry touched receives font-size from
;; main but keeps local width until frontend remasure.
;; main but keeps local width until frontend re-measure.
(let [;; ==== Setup
file0 (-> (thf/sample-file :file1)
(tho/add-frame-with-text :main-root :main-child "hello world")

View File

@ -1254,10 +1254,20 @@
(without-fills val))))))
operations)))
(defn- grow-type-after
"Grow type of text `shape` once `change` is applied."
[shape {:keys [operations]}]
(or (->> operations
(filter #(and (= :set (:type %)) (= :grow-type (:attr %))))
(last)
:val)
(:grow-type shape)))
(defn- sync-auto-grow-text-ids-on-page
"Auto-grow text ids from sync redo-changes on `page-id` that can change
the text size, resolved against pre-commit `objects`. Off-page, non-text
and :fixed ids are excluded."
"Text ids from sync redo-changes on `page-id` that are auto-grow once the
change is applied and whose size the change can alter. Shapes come from
pre-commit `objects`; the grow type comes from the change when it sets
one. Off-page, non-text and ids :fixed after the change are excluded."
[changes page-id objects]
(into []
(comp
@ -1265,7 +1275,7 @@
(filter (fn [{:keys [id] :as change}]
(when-let [shape (get objects id)]
(and (cfh/text-shape? shape)
(not= :fixed (:grow-type shape))
(not= :fixed (grow-type-after shape change))
(text-size-change? shape change)))))
(map :id)
(distinct))
@ -1281,47 +1291,54 @@
(dissoc state :updating-library)))))
(defn- sync-file-frontend-events
"Commit sync changes, schedule current-page auto-grow text remasure, then
layout. Remasure heals box size only; it does not clear a stale
:geometry-group flag. Keep per-page updated-frames layout and
thumbnail clears."
"Commit sync changes, schedule current-page auto-grow text re-measure, then
layout. Re-measure heals box size only; it does not clear a stale
:geometry-group flag. The re-measure commit carries
:skip-component-sync? so it does not start another sync; the resize
itself never marks :geometry-group (it uses :ignore-touched). Keep
per-page updated-frames layout and thumbnail clears.
An auto-grow text copy takes the main's width and height on each
geometry sync, also when its content is overridden: its size is derived,
not an override. The re-measure corrects it on the current page, and the
page-open check on other pages. Until then the viewer, exports and
thumbnails show the main's box."
[file-id changes updated-frames undo-group current-page-id objects wasm?]
(let [remasure-ids (when (and wasm? (some? current-page-id))
(sync-auto-grow-text-ids-on-page changes current-page-id objects))
(let [remeasure-ids (when (and wasm? (some? current-page-id))
(sync-auto-grow-text-ids-on-page changes current-page-id objects))
frames-by-page (group-by :page-id updated-frames)
;; Remasure-only layout when the current page has texts to heal but
;; Re-measure-only layout when the current page has texts to heal but
;; no synced frames entry (covers empty updated-frames too).
remasure-only-layout? (and (seq remasure-ids)
(nil? (get frames-by-page current-page-id)))]
remeasure-only-layout? (and (seq remeasure-ids)
(nil? (get frames-by-page current-page-id)))]
(rx/concat
(rx/of (set-updating-library false)
(ntf/hide {:tag :sync-dialog}))
(when (seq (:redo-changes changes))
(rx/of (dch/commit-changes changes)))
;; Schedule remasure before layout (swap pattern: debounce ~40ms vs
;; Schedule re-measure before layout (swap pattern: debounce ~40ms vs
;; layout buffer ~100ms).
(when (seq remasure-ids)
(rx/of (dwwt/resize-wasm-text-all remasure-ids
(when (seq remeasure-ids)
(rx/of (dwwt/resize-wasm-text-all remeasure-ids
{:skip-component-sync? true
:undo-group undo-group})))
(rx/merge
;; Per-page layout for synced frames; merge remasure ids into the
;; current page so hug sees the post-remasure box.
;; Per-page layout for synced frames; merge re-measure ids into the
;; current page so hug sees the post-re-measure box.
(->> frames-by-page
(map (fn [[page-id frames]]
(let [ids (cond-> (mapv :id frames)
(and (= page-id current-page-id)
(seq remasure-ids))
(into remasure-ids))]
(seq remeasure-ids))
(into remeasure-ids))]
(ptk/data-event :layout/update
{:page-id page-id
:ids ids
:undo-group undo-group}))))
(rx/from))
(when remasure-only-layout?
(when remeasure-only-layout?
(rx/of (ptk/data-event :layout/update
{:page-id current-page-id
:ids remasure-ids
:ids remeasure-ids
:undo-group undo-group})))
(->> (rx/from updated-frames)
(rx/mapcat
@ -1389,13 +1406,24 @@
ptk/WatchEvent
(watch [it state stream]
(when (and (some? file-id) (some? library-id)) ; Prevent race conditions while navigating out of the file
(log/info :msg "SYNC-FILE"
:file (debug-pretty-file file-id state)
:library (debug-pretty-file library-id state)
:asset-type asset-type
:asset-id asset-id
:undo-group undo-group)
(let [ldata (dsh/lookup-file-data state file-id)
(let [tx (dm/get-in state [:workspace-undo :transaction])
;; The sync commit and its text re-measure share one undo
;; group. The layout pass does not get it (the layout
;; buffer drops `:undo-group`); it joins the same undo
;; entry because it commits with `:stack-undo? true`.
;; Inside an undo transaction (color and typography edits)
;; the group is the transaction's, so the edit and its sync
;; undo and roll back together
undo-group (or undo-group (:undo-group tx) (:commit-group tx) (uuid/next))
_ (log/info :msg "SYNC-FILE"
:file (debug-pretty-file file-id state)
:library (debug-pretty-file library-id state)
:asset-type asset-type
:asset-id asset-id
:undo-group undo-group)
ldata (dsh/lookup-file-data state file-id)
libraries (dsh/lookup-libraries state)
current-file-id (:current-file-id state)

View File

@ -101,7 +101,7 @@
;; Never call this directly but through the data-event `:layout/update`
;; Otherwise a lot of cycle dependencies could be generated
(defn- update-layout-positions
[{:keys [page-id ids undo-group reflow-tasks save-undo?]}]
[{:keys [page-id ids undo-group reflow-tasks save-undo? skip-component-sync?]}]
(ptk/reify ::update-layout-positions
ptk/WatchEvent
(watch [_ state stream]
@ -118,12 +118,14 @@
(rx/of (dwm/apply-wasm-modifiers modif-tree
:stack-undo? true
:save-undo? save-undo?
:skip-component-sync? skip-component-sync?
:undo-group undo-group
:ignore-touched true))
(rx/of (dwm/apply-modifiers {:page-id page-id
:modifiers modif-tree
:stack-undo? true
:save-undo? save-undo?
:skip-component-sync? skip-component-sync?
:ignore-touched true
:undo-group undo-group}))))
(rx/empty))
@ -172,14 +174,20 @@
(rx/filter #(d/not-empty? %))
(rx/mapcat
(fn [updates]
;; Updates flagged `:save-undo? false` (automatic text size
;; heals) are laid out apart, so their reflow records no undo.
(->> (group-by (juxt :page-id #(not (false? (:save-undo? %)))) updates)
(map (fn [[[page-id save-undo?] updates]]
;; Updates flagged `:save-undo? false` and
;; `:skip-component-sync?` (automatic text size heals) are
;; laid out apart, so their reflow records no undo and does
;; not change components.
(->> (group-by (juxt :page-id
#(not (false? (:save-undo? %)))
#(boolean (:skip-component-sync? %)))
updates)
(map (fn [[[page-id save-undo? skip-component-sync?] updates]]
(let [ids (into #{} (mapcat :ids) updates)]
(update-layout-positions {:page-id page-id
:ids ids
:save-undo? save-undo?
:skip-component-sync? skip-component-sync?
:reflow-tasks (mapv ::reflow-task updates)})))))))
(rx/take-until stopper)
;; On workspace teardown clear everything still pending.

View File

@ -813,19 +813,6 @@
(defn not-changed? [old-dim new-dim]
(> (mth/abs (- old-dim new-dim)) 0.1))
(defn text-size-drifted?
"True when a measured auto-grow size is more than 1px off the stored one on
the axis that grows (width for :auto-width, height for both). Gaps up to
1px come from rounding differences between renderers and browsers. An
axis that fills its layout parent takes its size from the layout, so it
never drifts."
[{:keys [grow-type width height] :as shape} new-width new-height]
(or (and (= :auto-width grow-type)
(not (ctl/fill-width? shape))
(> (mth/abs (- width new-width)) 1))
(and (not (ctl/fill-height? shape))
(> (mth/abs (- height new-height)) 1))))
(defn commit-resize-text
[]
(ptk/reify ::commit-resize-text
@ -886,7 +873,9 @@
(rx/empty))
(rx/of (ptk/data-event :layout/update {:ids ids}))
(if (seq heal-ids)
(rx/of (ptk/data-event :layout/update {:ids heal-ids :save-undo? false}))
(rx/of (ptk/data-event :layout/update {:ids heal-ids
:save-undo? false
:skip-component-sync? true}))
(rx/empty))
(rx/of (dwu/commit-undo-transaction undo-id)))))))))

View File

@ -104,15 +104,16 @@
(defn- merge-resize-debounce-opts
"Merge the options of a request into its batch. The batch records no undo
step only when every request in it asked for that, so a user resize that
lands in the same window keeps its undo entry."
step, or skips the component sync, only when every request in it asked
for that, so a user resize that lands in the same window keeps its undo
entry and still reaches the copies."
[prev {:keys [undo-group undo-id skip-component-sync? save-undo?]}]
(-> (cond-> (or prev {})
(some? undo-group) (assoc :undo-group undo-group)
(some? undo-id) (assoc :undo-id undo-id)
skip-component-sync? (assoc :skip-component-sync? true))
(assoc :save-undo? (or (:save-undo? prev false)
(not (false? save-undo?))))))
(let [prev (or prev {:skip-component-sync? true :save-undo? false})]
(cond-> (assoc prev
:skip-component-sync? (and (:skip-component-sync? prev) (boolean skip-component-sync?))
:save-undo? (or (:save-undo? prev) (not (false? save-undo?))))
(some? undo-group) (assoc :undo-group undo-group)
(some? undo-id) (assoc :undo-id undo-id))))
(defn resize-wasm-text-debounce-commit
[]
@ -210,7 +211,7 @@
(defn resize-wasm-text-debounce
([id]
(resize-wasm-text-debounce id nil))
([id {:keys [undo-group undo-id skip-component-sync? save-undo?] :as opts}]
([id opts]
(ptk/reify ::resize-wasm-text-debounce
ptk/WatchEvent
(watch [_ state _]
@ -228,14 +229,8 @@
resize-wasm-stream
(if fonts-ready?
(let [pass-opts (when (or (some? undo-group) (some? undo-id) skip-component-sync?
(false? save-undo?))
(cond-> {}
(some? undo-group) (assoc :undo-group undo-group)
(some? undo-id) (assoc :undo-id undo-id)
skip-component-sync? (assoc :skip-component-sync? true)
(false? save-undo?) (assoc :save-undo? false)))]
(rx/of (resize-wasm-text-debounce-inner id pass-opts)))
;; `merge-resize-debounce-opts` reads only the keys it knows.
(rx/of (resize-wasm-text-debounce-inner id opts))
;; Fonts not loaded; retry after 20 msecs
(->> (rx/of (resize-wasm-text-debounce id opts))

View File

@ -14,6 +14,7 @@
[app.common.geom.shapes.text :as gsht]
[app.common.logging :as log]
[app.common.math :as mth]
[app.common.types.component :as ctk]
[app.common.types.modifiers :as ctm]
[app.common.types.text :as txt]
[app.common.uuid :as uuid]
@ -92,22 +93,29 @@
(defn- text-heal
"How to commit a measured auto-grow text in heal `phase`: nil commits
nothing, otherwise a map with the commit `:opts` and the `:next` heal
phase, if any.
The `:check` phase runs when the page opens. It commits when the size
drifted, so rounding differences between renderers or browsers are not
written back on every open, or when the text has no position-data. A heal
records no undo step. A resize makes the text be measured again at its new
box, in the `:settle` phase, which is part of the heal too. Without a phase
the text is committed as usual."
nothing, otherwise a map with the commit `:opts`, whether to `:resize?`
the text and the `:next` heal phase, if any.
The `:check` phase runs when the page opens. It resizes the text when the
size drifted, so rounding differences between renderers or browsers are
not written back on every open. A text with no position-data that did not
drift gets its position-data only. A heal records no undo step. A resize
makes the text be measured again at its new box, in the `:settle` phase,
which is part of the heal too. Without a phase the text is committed as
usual.
Known limit: the WebGL and SVG renderers can measure the same text
differently. When they differ by more than 1px, each page open by a user
of the other renderer writes the size back. Two browsers on the SVG
renderer can do the same: a long auto-width line can differ by more than
1px, and an auto-height text can wrap a line differently."
[phase shape size]
(case phase
:check (let [drifted? (and (some? size) (apply dwt/text-size-drifted? shape size))]
:check (let [drifted? (when-let [[width height] size]
(gsht/text-size-drifted? shape width height 1))]
(when (or drifted? (nil? (:position-data shape)))
(cond-> {:opts {:save-undo? false}}
drifted? (assoc :next :settle))))
:settle {:opts {:save-undo? false}}
{}))
drifted? (assoc :resize? true :next :settle))))
:settle {:opts {:save-undo? false} :resize? true}
{:resize? true}))
(defn- update-text-shape
"Measure the text and commit its position-data and auto-grow size as
@ -115,7 +123,11 @@
[{:keys [id] :as shape} node phase]
(->> (tsp/calc-position-data id)
(p/fmap (fn [position-data]
(let [size (measured-auto-size shape node)
(let [;; A page-open check never writes a size laid out
;; with a fallback font
size (when-not (and (= :check phase)
(tsp/font-failed? position-data))
(measured-auto-size shape node))
heal (text-heal phase shape size)
opts (:opts heal)]
(when (some? heal)
@ -123,7 +135,7 @@
(when (gsht/overlaps-position-data? shape position-data)
(st/emit! (dwt/update-position-data id position-data opts)))
(when-let [[width height] size]
(when-let [[width height] (and (:resize? heal) size)]
(st/emit! (dwt/resize-text id width height opts))))
(st/emit! (dwt/clean-text-modifier id))
@ -205,15 +217,18 @@
(nil? (:position-data new-shape))
(= :check phase))))
(defn override-copy-heal-phases
"Auto-grow texts whose content is overridden on a copy, each in the `:check`
heal phase: a component sync can give them the main's size, so they are
measured again when the page opens."
(defn copy-heal-phases
"Auto-grow texts inside a component copy, each in the `:check` heal phase:
a component sync, also one through a nested main, can give them a stale
size, so they are measured again when the page opens. Texts of a main are
never synced. The check runs on every mount of `viewport-texts`: a page
open, a version change, and the end of read-only mode (Inspect, save-lock
release), which unmounts it."
[text-shapes]
(into {}
(comp (map val)
(filter (comp #{:auto-width :auto-height} :grow-type))
(filter #(contains? (:touched %) :content-group))
(filter ctk/in-component-copy?)
(map (fn [{:keys [id]}] [id :check])))
text-shapes))
@ -229,11 +244,11 @@
pending-update* (mf/use-state {})
pending-update (deref pending-update*)
;; Heal phase per text id. Copies whose text is overridden start in
;; Heal phase per text id. Auto-grow texts in copies start in
;; `:check` and are measured on page open: a sync while their page was
;; closed can give them the main's size. A text in `:settle` waits for
;; closed can give them a stale size. A text in `:settle` waits for
;; its heal resize to change the shape, which measures it again.
phases* (mf/use-state #(override-copy-heal-phases text-shapes))
phases* (mf/use-state #(copy-heal-phases text-shapes))
phases (deref phases*)
text-change?

View File

@ -14,6 +14,7 @@
[app.common.files.focus :as cpf]
[app.common.files.helpers :as cfh]
[app.common.fonts :as cfnt]
[app.common.geom.shapes.text :as gsht]
[app.common.logging :as log]
[app.common.math :as mth]
[app.common.render-wasm.api.props :as props]
@ -1661,16 +1662,13 @@
[text-ids]
(run! f/force-update-text-layout text-ids))
(defn- text-selrect-stale?
(defn- text-size-stale?
"Check if the WASM-measured dimensions of an auto-grow text shape differ
from its stored selrect by more than `tolerance`."
[{:keys [id selrect grow-type]} tolerance]
from its stored size by more than `tolerance` on an axis that grows and
does not fill its layout parent."
[{:keys [id] :as shape} tolerance]
(when-let [{:keys [width height]} (get-text-dimensions id)]
(case grow-type
:auto-width (or (not (mth/close? width (:width selrect) tolerance))
(not (mth/close? height (:height selrect) tolerance)))
:auto-height (not (mth/close? height (:height selrect) tolerance))
false)))
(gsht/text-size-drifted? shape width height tolerance)))
(defonce ^:private pending-stale-selrect-ids (atom #{}))
(defonce ^:private stale-selrect-sync-token (atom 0))
@ -1696,8 +1694,9 @@
(listen-tiles-render-complete-once! flush-on-idle!)))
(defn- sync-stale-text-selrects!
"Emit the ids of auto-grow text shapes whose selrect no longer matches the
measured layout, so the workspace resizes them (data-event instead of a
"Emit the ids of auto-grow text shapes whose stored size drifted from the
measured layout on an axis that grows and does not fill its layout
parent, so the workspace resizes them (data-event instead of a
direct call to avoid a circular dependency; see the watcher in
`app.main.data.workspace/initialize-workspace`). The default tolerance is
0.1px, as in the classic renderer."
@ -1707,7 +1706,7 @@
(let [stale-ids (into []
(comp (filter cfh/text-shape?)
(filter (comp #{:auto-width :auto-height} :grow-type))
(filter #(text-selrect-stale? % tolerance))
(filter #(text-size-stale? % tolerance))
(map :id))
shapes)]
(when (seq stale-ids)

View File

@ -40,6 +40,8 @@
load-promise)))
(defn resolve-font
"Ensure the font of `node` is loaded. Resolves to `::font-failed` when it
cannot be loaded: the text is then laid out with a fallback font."
[node]
(let [styles (dom/get-computed-styles node)
font (dom/get-property-value styles "font")
@ -59,7 +61,7 @@
(load-font font))))
(p/merr (fn [_cause]
(js/console.error (str/ffmt "Cannot load font %" font-id))
(p/resolved nil))))))
(p/resolved ::font-failed))))))
(defn- process-text-node
@ -84,7 +86,15 @@
(let [text-nodes (-> (dom/query (dm/fmt "#html-text-node-%" shape-id))
(dom/query-all ".text-node"))]
(->> (p/all (map resolve-font text-nodes))
(p/fmap #(mapcat process-text-node text-nodes)))))
(p/fmap (fn [fonts]
(cond-> (into [] (mapcat process-text-node) text-nodes)
(some #{::font-failed} fonts)
(with-meta {::font-failed true})))))))
(defn font-failed?
"True when `position-data` was measured with a font that failed to load."
[position-data]
(true? (::font-failed (meta position-data))))
(defn calc-position-data
[shape-id]
@ -113,4 +123,5 @@
(when (some? shape-id)
(->> (calc-text-node-positions shape-id)
(p/fmap (fn [text-data]
(mapv transform-data text-data)))))))
(with-meta (mapv transform-data text-data)
(meta text-data))))))))

View File

@ -9,19 +9,23 @@
user action) must not record an undo step, so Ctrl+Z reverts the user's
own last edit."
(:require
[app.common.math :as mth]
[app.common.test-helpers.compositions :as ctho]
[app.common.test-helpers.files :as cthf]
[app.common.test-helpers.ids-map :as cthi]
[app.common.test-helpers.shapes :as cths]
[app.main.data.changes :as dch]
[app.main.data.helpers :as dsh]
[app.main.data.workspace.shape-layout :as dwsl]
[app.main.data.workspace.texts :as dwt]
[app.main.data.workspace.undo :as dwu]
[app.main.data.workspace.wasm-text :as dwwt]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
[frontend-tests.helpers.async :as async]
[frontend-tests.helpers.state :as ths]
[frontend-tests.helpers.wasm :as thw]
[frontend-tests.tokens.helpers.state :as tohs]
[potok.v2.core :as ptk]))
(t/use-fixtures :each
@ -66,7 +70,11 @@
(def ^:private heal {:skip-component-sync? true :save-undo? false})
(def ^:private user {:skip-component-sync? true})
;; What the component sync sends when it re-measures the synced copies.
(def ^:private sync-remeasure {:skip-component-sync? true})
;; A user resize carries no options.
(def ^:private user nil)
(t/deftest ^:async heal-resize-records-no-undo-step
(let [{:keys [commit]} (await (batch-commit heal))]
@ -76,28 +84,67 @@
(t/deftest ^:async user-resize-keeps-its-undo-step
(let [{:keys [commit]} (await (batch-commit user))]
(t/is (true? (:save-undo? commit))
"a resize without the flag records undo as today")))
"a user resize records undo")
(t/is (not (:skip-component-sync? commit))
"a user resize syncs to component copies")))
(t/deftest ^:async sync-remeasure-keeps-its-undo-step
(let [{:keys [commit]} (await (batch-commit sync-remeasure))]
(t/is (true? (:save-undo? commit))
"a sync re-measure records undo")
(t/is (true? (:skip-component-sync? commit))
"a sync re-measure does not start another sync")))
(t/deftest ^:async user-resize-batched-after-a-heal-keeps-its-undo-step
(let [{:keys [commit ids]} (await (batch-commit heal nil))]
(let [{:keys [commit ids]} (await (batch-commit heal user))]
(t/is (every? #(touches? commit %) ids)
"both resizes land in one commit")
(t/is (true? (:save-undo? commit))
"a user resize without options keeps its undo step")))
"a user resize without options keeps its undo step")
(t/is (not (:skip-component-sync? commit))
"a user resize without options still syncs to component copies")))
(t/deftest ^:async heal-batched-after-a-user-resize-keeps-the-undo-step
(let [{:keys [commit ids]} (await (batch-commit nil heal))]
(let [{:keys [commit ids]} (await (batch-commit user heal))]
(t/is (every? #(touches? commit %) ids)
"both resizes land in one commit")
(t/is (true? (:save-undo? commit))
"the user's resize keeps its undo step")))
"the user's resize keeps its undo step")
(t/is (not (:skip-component-sync? commit))
"the user's resize still syncs to component copies")))
(t/deftest ^:async user-resize-batched-after-a-sync-remeasure-still-syncs
(let [{:keys [commit ids]} (await (batch-commit sync-remeasure user))]
(t/is (every? #(touches? commit %) ids)
"both resizes land in one commit")
(t/is (true? (:save-undo? commit)))
(t/is (not (:skip-component-sync? commit))
"the main's new size reaches its copies")))
(t/deftest ^:async sync-remeasure-batched-after-a-user-resize-still-syncs
(let [{:keys [commit ids]} (await (batch-commit user sync-remeasure))]
(t/is (every? #(touches? commit %) ids)
"both resizes land in one commit")
(t/is (true? (:save-undo? commit)))
(t/is (not (:skip-component-sync? commit))
"the main's new size reaches its copies")))
(t/deftest ^:async batch-of-sync-remeasures-skips-the-sync
(let [{:keys [commit ids]} (await (batch-commit sync-remeasure sync-remeasure))]
(t/is (every? #(touches? commit %) ids)
"both re-measures land in one commit")
(t/is (true? (:save-undo? commit)))
(t/is (true? (:skip-component-sync? commit))
"a batch of re-measures does not start another sync")))
(t/deftest ^:async batch-of-heals-records-no-undo-step
(let [{:keys [commit ids]} (await (batch-commit heal heal))]
(t/is (every? #(touches? commit %) ids)
"both heals land in one commit")
(t/is (false? (:save-undo? commit))
"a batch of heals is not added to the undo history")))
"a batch of heals is not added to the undo history")
(t/is (true? (:skip-component-sync? commit))
"a batch of heals does not sync to component copies")))
;; SVG renderer
@ -124,8 +171,11 @@
"the heal commit is not added to the undo history")
(t/is (true? (:skip-component-sync? (first @commits)))
"the heal does not sync to component copies")
(t/is (some #(and (false? (:save-undo? %)) (contains? (set (:ids %)) id)) @layouts)
"the parents' reflow is asked for without undo too")))
(t/is (some #(and (false? (:save-undo? %))
(true? (:skip-component-sync? %))
(contains? (set (:ids %)) id))
@layouts)
"the parents' reflow is asked for without undo and without sync too")))
(defn- ^:async svg-mixed-commits
"Emit `heal-event` for one text and `user-event` for another in the same
@ -225,12 +275,84 @@
user (collect-commits store rect-b)]
(ptk/emit! store (dwsl/initialize-shape-layout))
;; Both updates land in the same 100 ms layout buffer.
(ptk/emit! store (ptk/data-event :layout/update {:ids [rect-a] :save-undo? false}))
(ptk/emit! store (ptk/data-event :layout/update {:ids [rect-a]
:save-undo? false
:skip-component-sync? true}))
(ptk/emit! store (ptk/data-event :layout/update {:ids [rect-b]}))
(await (async/wait-for #(and (seq @heal) (seq @user)) "a reflow commit for each board"
{:max-ticks 400}))
(ptk/emit! store (dwsl/finalize-shape-layout))
(t/is (false? (:save-undo? (first @heal)))
"the reflow of a heal is not added to the undo history")
;; A commit without undo and without this flag would make the component
;; watcher touch the component, so a page open would change it
(t/is (true? (:skip-component-sync? (first @heal)))
"the reflow of a heal does not change components")
(t/is (true? (:save-undo? (first @user)))
"a user reflow in the same buffer keeps its undo step")))
"a user reflow in the same buffer keeps its undo step")
(t/is (not (:skip-component-sync? (first @user)))
"and still syncs to component copies")))
;; Undo history
(defn- undo-stack
[store]
(select-keys (:workspace-undo @store) [:items :index]))
(defn- text-size
[store id]
(-> (dsh/lookup-page-objects @store)
(get id)
(select-keys [:width :height])))
(defn- ^:async heal-keeps-the-undo-history
"Make a user edit on one text with `user-event`, then heal another with
`heal-event`, each in its own commit. The heal must leave the undo stack
as the user edit left it, and undo must revert the user edit."
[renderer user-event heal-event]
(let [file (-> (cthf/sample-file :file1)
(ctho/add-frame-with-text :frame-a :text-a "hello")
(ctho/add-frame-with-text :frame-b :text-b "world"))
store (ths/setup-store file (when renderer {:renderer renderer}))
user-id (:id (cths/get-shape file :text-a))
heal-id (:id (cths/get-shape file :text-b))
user-commits (collect-commits store user-id)
heal-commits (collect-commits store heal-id)
original (text-size store user-id)]
(ptk/emit! store (tohs/watch-undo-stack))
(ptk/emit! store (user-event user-id))
(await (async/wait-for #(and (seq @user-commits) (seq (:items (undo-stack store))))
"an undo entry for the user edit" {:max-ticks 200}))
(let [after-user (undo-stack store)
edited (text-size store user-id)]
(t/is (not= original edited)
"the user edit changes the text size")
(ptk/emit! store (heal-event heal-id))
(await (async/wait-for #(seq @heal-commits) "a heal commit" {:max-ticks 200}))
(await (async/settle))
(let [healed (text-size store heal-id)]
(t/is (= after-user (undo-stack store))
"the heal adds no undo entry and does not move the index")
(ptk/emit! store dwu/undo)
(await (async/wait-for #(not= edited (text-size store user-id))
"the undo of the user edit" {:max-ticks 200}))
(t/is (and (mth/close? (:width original) (:width (text-size store user-id)))
(mth/close? (:height original) (:height (text-size store user-id))))
"undo reverts the user edit")
(t/is (= healed (text-size store heal-id))
"undo leaves the heal in place")))))
(t/deftest ^:async heal-keeps-the-undo-history-on-wasm
(await (heal-keeps-the-undo-history
nil
#(dwwt/resize-wasm-text-all [%] nil)
#(dwwt/resize-wasm-text-all [%] heal))))
(t/deftest ^:async heal-keeps-the-undo-history-on-svg
(await (heal-keeps-the-undo-history
:svg
#(dwt/resize-text % 60 40)
#(dwt/resize-text % 50 30 {:save-undo? false}))))

View File

@ -6,8 +6,9 @@
(ns frontend-tests.data.workspace-sync-text-wasm-test
"Regression test for #12721: after component sync with render-wasm/v1,
auto-grow text copies must be scheduled for WASM remasure with
:skip-component-sync? so box size heals without marking :geometry-group."
auto-grow text copies must be scheduled for a WASM re-measure with
:skip-component-sync?, so the re-measure commit does not start another
sync."
(:require
[app.common.files.changes-builder :as pcb]
[app.common.geom.shapes :as gsh]
@ -19,7 +20,9 @@
[app.common.test-helpers.shapes :as cths]
[app.common.types.modifiers :as ctm]
[app.common.uuid :as uuid]
[app.main.data.changes :as dch]
[app.main.data.workspace.libraries :as dwl]
[app.main.data.workspace.undo :as dwu]
[app.main.data.workspace.wasm-text :as dwwt]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
@ -92,7 +95,7 @@
(rx/subs! (fn [_] nil)))
acc))
(t/deftest test-sync-file-schedules-wasm-text-remasure
(t/deftest test-sync-file-schedules-wasm-text-remeasure
(t/async
done
(let [file (-> (setup-file) bump-main-font-size)
@ -118,15 +121,114 @@
(mapcat :ids)
set)]
(t/is (some #{copy-id} ids)
"remasure ids should include the copy text")
"re-measure ids should include the copy text")
(t/is (:skip-component-sync? opts)
"remasure must use :skip-component-sync? so size heal does not mark :geometry-group")
"re-measure must use :skip-component-sync? so its commit does not start another sync")
(t/is (= undo-group (:undo-group opts)))
(t/is (every? layout-ids ids)
(str "current-page :layout/update ids must include remasure ids; "
"layout=" layout-ids " remasure=" ids))))))))
(str "current-page :layout/update ids must include re-measure ids; "
"layout=" layout-ids " re-measure=" ids))))))))
(t/deftest test-sync-file-skips-remasure-for-fixed-text
(defn- collect-commits
"Subscribe before emit; accumulates the commits that touch `id`."
[store id]
(let [acc (atom [])]
(->> (ptk/input-stream store)
(rx/filter dch/commit?)
(rx/map deref)
(rx/filter #(some (comp #{id} :id) (:redo-changes %)))
(rx/subs! #(swap! acc conj %)))
acc))
(t/deftest test-sync-file-without-undo-group-shares-one-with-its-remeasure
(t/async
done
(let [file (-> (setup-file) bump-main-font-size)
store (ths/setup-store file)
copy-id (:id (cths/get-shape file :copy-child))
commits (collect-commits store copy-id)
;; The library update dialog and the color and typography syncs
;; pass no undo group
events [(dwl/sync-file (:id file) (:id file)
:components (cthi/id :component1))]]
(ths/run-store
store done events
(fn [_]
(let [sync-group (:undo-group (first @commits))
remeasure-opts (:opts (first @resize-calls))]
(t/is (some? sync-group)
"the sync commit gets an undo group")
(t/is (= sync-group (:undo-group remeasure-opts))
"the re-measure shares it, so one undo reverts both")))))))
(defn- run-sync-in-undo-transaction
"Runs, inside one undo transaction, an edit commit with `edit-group` (nil
for none) and then `sync-file` with no undo group, and checks that the
sync commit and its re-measure take the edit's group. With `edit-group`
the edit's history entry is appended by hand, as the workspace undo
watcher does, so the transaction gets that group as its `:undo-group`."
[done edit-group]
(let [file (-> (setup-file) bump-main-font-size)
store (ths/setup-store file)
page-id (cthf/current-page-id file)
tx (js/Symbol)
redo [{:type :mod-page :id page-id :name "Edited"}]
undo [{:type :mod-page :id page-id :name "Page 1"}]
groups (atom [])
sub (->> (ptk/input-stream store)
(rx/filter dch/commit?)
(rx/subs! #(swap! groups conj (:undo-group (deref %)))))
events (cond-> [(dwu/start-undo-transaction tx :timeout 0)
;; Stands for the color, typography or delete commit
(dch/commit-changes {:redo-changes redo
:undo-changes undo
:undo-group edit-group})]
(some? edit-group)
(conj (dwu/append-undo {:undo-changes undo
:redo-changes redo
:undo-group edit-group
:tags #{}}
false))
:always
(conj (dwl/sync-file (:id file) (:id file)
:components (cthi/id :component1))
(dwu/commit-undo-transaction tx)))]
(ths/run-store
store done events
(fn [_]
(rx/dispose! sub)
(let [first-group (first @groups)
remeasure-opts (:opts (first @resize-calls))]
(t/is (some? first-group))
(when (some? edit-group)
(t/is (= edit-group first-group)))
(t/is (< 1 (count @groups))
"the sync commits after the edit")
(t/is (every? #{first-group} @groups)
"the sync commit takes the transaction's group")
(t/is (= first-group (:undo-group remeasure-opts))
"the re-measure takes the transaction's group"))))))
;; Scenario: the color and typography edits commit and call `sync-file`
;; with no undo group inside their own undo transaction. Proves: the sync
;; commit and its re-measure take the transaction's group, so one undo
;; reverts the edit and its sync, and a rejected sync rolls back both.
(t/deftest test-sync-file-in-undo-transaction-shares-its-group
(t/async
done
(run-sync-in-undo-transaction done nil)))
;; Scenario: `delete-component` commits with its own undo group inside the
;; sidebar's undo transaction, then syncs with no group. Proves: the sync
;; takes the transaction's `:undo-group` (the delete's), not the group the
;; transaction was opened with.
(t/deftest test-sync-file-in-undo-transaction-takes-the-entry-group
(t/async
done
(run-sync-in-undo-transaction done (uuid/next))))
(t/deftest test-sync-file-skips-remeasure-for-fixed-text
(t/async
done
(let [file (-> (setup-file :grow-type :fixed) bump-main-font-size)
@ -140,7 +242,50 @@
store done events
(fn [_new-state]
(t/is (empty? @resize-calls)
"fixed-grow texts must not be scheduled for WASM remasure"))))))
"fixed-grow texts must not be scheduled for a WASM re-measure"))))))
(defn- set-main-grow-type
[grow-type]
(fn [file]
(update-main-text file #(assoc % :grow-type grow-type))))
(t/deftest test-sync-file-remeasures-text-that-becomes-auto-grow
(t/async
done
(let [file (-> (setup-file :grow-type :fixed)
((set-main-grow-type :auto-height)))
store (ths/setup-store file)
copy-id (:id (cths/get-shape file :copy-child))
events [(dwl/sync-file (:id file) (:id file)
:components (cthi/id :component1))]]
(ths/run-store
store done events
(fn [_]
(t/is (= 1 (count @resize-calls))
"a copy turned auto-grow by the sync is re-measured")
(t/is (some #{copy-id} (:ids (first @resize-calls)))
"the re-measure includes the copy"))))))
(t/deftest test-sync-file-skips-text-that-becomes-fixed
(t/async
done
(let [file (-> (setup-file :grow-type :auto-height)
((set-main-grow-type :fixed)))
store (ths/setup-store file)
page-id (cthf/current-page-id file)
copy-id (:id (cths/get-shape file :copy-child))
layout-updates (collect-layout-updates store)
events [(dwl/sync-file (:id file) (:id file)
:components (cthi/id :component1))]]
(ths/run-store
store done events
(fn [_]
(t/is (empty? @resize-calls)
"a copy turned fixed by the sync is not re-measured")
(t/is (not-any? #(and (= page-id (:page-id %))
(some #{copy-id} (:ids %)))
@layout-updates)
"and gets no layout update for a re-measure"))))))
(defn- sync-remeasures
"Sync the copy after `change-main` and call `check` with the re-measure
@ -152,7 +297,7 @@
:components (cthi/id :component1))]]
(ths/run-store store done events (fn [_] (check @resize-calls)))))
(t/deftest test-sync-file-skips-remasure-for-fill-change
(t/deftest test-sync-file-skips-remeasure-for-fill-change
(t/async
done
(sync-remeasures done recolor-main-text
@ -160,7 +305,7 @@
(t/is (empty? calls)
"a text color change does not change its size")))))
(t/deftest test-sync-file-skips-remasure-for-opacity-change
(t/deftest test-sync-file-skips-remeasure-for-opacity-change
(t/async
done
(sync-remeasures done fade-main-text
@ -168,7 +313,7 @@
(t/is (empty? calls)
"an opacity change does not change the text size")))))
(t/deftest test-sync-file-remasures-auto-height-text-on-font-change
(t/deftest test-sync-file-remeasures-auto-height-text-on-font-change
(t/async
done
(sync-remeasures done bump-main-font-size
@ -176,7 +321,7 @@
(t/is (= 1 (count calls))
"a font change can change the text size")))))
(t/deftest test-sync-file-remasures-auto-height-text-on-width-change
(t/deftest test-sync-file-remeasures-auto-height-text-on-width-change
(t/async
done
(sync-remeasures done widen-main-text

View File

@ -769,35 +769,3 @@
(t/deftest same-styled-text-sees-a-text-change
(t/is (not (dwt/same-styled-text? (text-content {:text "Hello" :font-weight "400"})
(text-content {:text "Hello!" :font-weight "400"})))))
(t/deftest text-size-drifted-ignores-sub-pixel-gaps
(t/is (not (dwt/text-size-drifted? {:grow-type :auto-width :width 100 :height 17} 100.5 17.5)))
(t/is (not (dwt/text-size-drifted? {:grow-type :auto-height :width 100 :height 17} 100 17.5))))
(t/deftest text-size-drifted-checks-only-the-growing-axis
(t/is (not (dwt/text-size-drifted? {:grow-type :auto-height :width 100 :height 17} 140 17))
"auto-height width comes from the box, not the text")
(t/is (dwt/text-size-drifted? {:grow-type :auto-height :width 100 :height 17} 100 34))
(t/is (dwt/text-size-drifted? {:grow-type :auto-width :width 44 :height 17} 67 17))
(t/is (dwt/text-size-drifted? {:grow-type :auto-width :width 44 :height 17} 44 34)
"auto-width grows in height too"))
(t/deftest text-size-drifted-treats-exactly-one-pixel-as-rounding
(t/is (not (dwt/text-size-drifted? {:grow-type :auto-height :width 100 :height 17} 100 18))
"a 1px height gap is rounding, as in the WebGL check")
(t/is (not (dwt/text-size-drifted? {:grow-type :auto-width :width 44 :height 17} 45 17))
"a 1px width gap is rounding, as in the WebGL check"))
(t/deftest text-size-drifted-ignores-an-axis-that-fills-its-parent
(t/is (not (dwt/text-size-drifted? {:grow-type :auto-height :width 100 :height 40
:layout-item-v-sizing :fill}
100 17))
"a height set by the layout is not drift")
(t/is (not (dwt/text-size-drifted? {:grow-type :auto-width :width 200 :height 17
:layout-item-h-sizing :fill}
44 17))
"a width set by the layout is not drift")
(t/is (dwt/text-size-drifted? {:grow-type :auto-width :width 200 :height 17
:layout-item-h-sizing :fill}
44 34)
"the axis that does not fill is still checked"))

View File

@ -22,12 +22,17 @@
[promesa.core :as p]))
(defn- text-shape
[grow-type width height]
{:id (uuid/next)
:type :text
:parent-id uuid/zero
:grow-type grow-type
:selrect {:x 0 :y 0 :width width :height height}})
([grow-type width height]
(text-shape grow-type width height nil))
([grow-type width height attrs]
(merge {:id (uuid/next)
:type :text
:parent-id uuid/zero
:grow-type grow-type
:width width
:height height
:selrect {:x 0 :y 0 :width width :height height}}
attrs)))
(defn- rect-shape
[]
@ -133,6 +138,22 @@
(t/is (empty? (stale-selrect-ids events))
"fixed text boxes are never resized to their layout")))
(t/deftest ^:async page-load-skips-axes-that-fill-their-layout-parent
(let [fill-width (text-shape :auto-width 200 17 {:layout-item-h-sizing :fill})
fill-height (text-shape :auto-height 100 40 {:layout-item-v-sizing :fill})
events (await (load-page (page-objects fill-width fill-height)
{(:id fill-width) {:width 44 :height 17}
(:id fill-height) {:width 100 :height 17}}))]
(t/is (empty? (stale-selrect-ids events))
"a size set by the layout is not stale")))
(t/deftest ^:async page-load-checks-the-axis-that-does-not-fill
(let [text (text-shape :auto-width 200 17 {:layout-item-h-sizing :fill})
events (await (load-page (page-objects text)
{(:id text) {:width 44 :height 34}}))]
(t/is (= #{(:id text)} (stale-selrect-ids events))
"the height of a fill-width auto-width text still grows with its content")))
(t/deftest ^:async page-load-skips-texts-waiting-for-a-font
(let [waiting (text-shape :auto-height 100 17)
ready (text-shape :auto-height 100 17)

View File

@ -7,10 +7,16 @@
(ns frontend-tests.ui.viewport-texts-html-test
"How the SVG renderer measures text shapes and commits the result."
(:require
["jsdom" :refer [JSDOM]]
["react" :as react]
["react-dom" :as rd]
["react-dom/client" :as rdc]
[app.common.geom.point :as gpt]
[app.common.uuid :as uuid]
[app.main.data.workspace.reflow :as wrf]
[app.main.data.workspace.texts :as dwt]
[app.main.store :as st]
[app.main.ui.shapes.text.html-text :as html]
[app.main.ui.workspace.shapes.text.viewport-texts-html :as vth]
[app.util.dom :as dom]
[app.util.text-svg-position :as tsp]
@ -18,7 +24,8 @@
[frontend-tests.helpers.async :as async]
[frontend-tests.helpers.mock :as mock]
[potok.v2.core :as ptk]
[promesa.core :as p]))
[promesa.core :as p]
[rumext.v2 :as mf]))
(def ^:private fixed-text
{:id (uuid/next) :type :text :grow-type :fixed})
@ -89,40 +96,53 @@
[& shapes]
(into {} (map (juxt :id identity)) shapes))
(t/deftest override-copy-heal-phases-checks-overridden-auto-grow-copies
(let [fixed (text :fixed #{:content-group})
untouched (text :auto-height nil)
geometry (text :auto-height #{:geometry-group})
unknown (text nil #{:content-group})
override (text :auto-width #{:content-group})]
(t/is (= {(:id override) :check}
(vth/override-copy-heal-phases (by-id fixed untouched geometry unknown override)))
"only auto-grow texts with overridden content are checked")))
(defn- in-copy
[shape]
(assoc shape :shape-ref (uuid/next)))
(t/deftest copy-heal-phases-checks-auto-grow-texts-in-copies
(let [fixed (in-copy (text :fixed #{:content-group}))
unknown (in-copy (text nil #{:content-group}))
main (text :auto-height #{:content-group})
untouched (in-copy (text :auto-height nil))
geometry (in-copy (text :auto-height #{:geometry-group}))
override (in-copy (text :auto-width #{:content-group}))]
(t/is (= {(:id untouched) :check
(:id geometry) :check
(:id override) :check}
(vth/copy-heal-phases (by-id fixed unknown main untouched geometry override)))
(str "every auto-grow text in a copy is checked, also one nested in a "
"main that overrides it, which has no touched flag of its own; "
"texts of a main and fixed texts are not"))))
(t/deftest unchanged-copy-is-measured-in-the-check-phase
(let [copy (text :auto-height #{:content-group})]
(t/is (vth/text-changed? copy copy :check)
"an unchanged copy waiting for its check is measured")
(t/is (not (vth/text-changed? copy copy nil))
"once checked, an unchanged copy is left alone")))
"once checked, an unchanged copy is left alone")
(t/is (not (vth/text-changed? copy copy :settle))
"a copy waiting to settle is measured only once its heal resize changes it")))
(defn- measure-with-box
"Measure `shape` in heal `phase` with its layout box measured at `width` x
`height`. Resolves to the events emitted to the store and the next heal
phase. The resize and position-data requests are recorded as `::resize`
and `::position-data` events carrying their options."
[shape phase width height]
(let [emitted (atom [])
record (fn [type] (fn [& args] (ptk/data-event type {:opts (last args)})))]
(->> (mock/with-mocks*
{tsp/calc-position-data (mock/stub (constantly (p/resolved [fragment])))
dom/query (mock/stub (constantly #js {}))
dom/get-bounding-rect (mock/stub (constantly {:width width :height height}))
dwt/resize-text (mock/stub (record ::resize))
dwt/update-position-data (mock/stub (record ::position-data))
st/emit! (mock/stub (fn [& events] (swap! emitted into events) nil))}
(await (measure-text shape #js {} phase)))
(p/fmap (fn [next-phase] {:events @emitted :next next-phase})))))
([shape phase width height]
(measure-with-box shape phase width height [fragment]))
([shape phase width height position-data]
(let [emitted (atom [])
record (fn [type] (fn [& args] (ptk/data-event type {:opts (last args)})))]
(->> (mock/with-mocks*
{tsp/calc-position-data (mock/stub (constantly (p/resolved position-data)))
dom/query (mock/stub (constantly #js {}))
dom/get-bounding-rect (mock/stub (constantly {:width width :height height}))
dwt/resize-text (mock/stub (record ::resize))
dwt/update-position-data (mock/stub (record ::position-data))
st/emit! (mock/stub (fn [& events] (swap! emitted into events) nil))}
(await (measure-text shape #js {} phase)))
(p/fmap (fn [next-phase] {:events @emitted :next next-phase}))))))
(defn- committed
"Options of the `type` request among `events`, `::none` if there is none."
@ -159,9 +179,21 @@
{:keys [events next]} (await (measure-with-box copy :check 200 17.4))]
(t/is (= no-undo (committed ::position-data events))
"a copy that lost its position-data in a sync gets it back, with no undo step")
(t/is (= ::none (committed ::resize events))
"a copy whose size did not drift is not resized")
(t/is (nil? next)
"nothing resizes it, so the heal ends")))
(t/deftest ^:async check-phase-heals-a-drifted-copy-without-position-data
(let [copy (assoc (text :auto-height #{:content-group}) :position-data nil)
{:keys [events next]} (await (measure-with-box copy :check 200 34))]
(t/is (= no-undo (committed ::resize events))
"a drifted copy without position-data is resized, with no undo step")
(t/is (= no-undo (committed ::position-data events))
"and gets its position-data back, with no undo step")
(t/is (= :settle next)
"the measurement caused by the resize belongs to the heal")))
(t/deftest ^:async check-phase-commits-nothing-when-it-cannot-measure
(let [{:keys [events]}
(await (measure-with-box (text :auto-height #{:content-group}) :check 0 0))]
@ -188,3 +220,146 @@
(t/is (= {} (committed ::position-data events))
"and so is the position-data")
(t/is (nil? next))))
(def ^:private fallback-font-position-data
"Position-data measured with a font that failed to load."
(with-meta [fragment] {::tsp/font-failed true}))
(t/deftest font-failed-reads-the-measurement-mark
(t/is (tsp/font-failed? fallback-font-position-data))
(t/is (not (tsp/font-failed? [fragment]))))
(t/deftest ^:async check-phase-writes-no-size-from-a-fallback-font
(let [{:keys [events next]}
(await (measure-with-box (text :auto-height #{:content-group}) :check 200 34
fallback-font-position-data))]
(t/is (= ::none (committed ::resize events))
"a size laid out with a fallback font is not written on page open")
(t/is (= ::none (committed ::position-data events))
"nor its position-data")
(t/is (nil? next)
"the heal ends")))
(t/deftest ^:async check-phase-restores-position-data-with-a-fallback-font
(let [copy (assoc (text :auto-height #{:content-group}) :position-data nil)
{:keys [events]}
(await (measure-with-box copy :check 200 34 fallback-font-position-data))]
(t/is (= no-undo (committed ::position-data events))
"a copy without position-data still gets it, with no undo step")
(t/is (= ::none (committed ::resize events))
"but its size is not written")))
(t/deftest ^:async no-phase-commits-a-fallback-font-size-as-usual
(let [{:keys [events]}
(await (measure-with-box (text :auto-height nil) nil 200 34
fallback-font-position-data))]
(t/is (= {} (committed ::resize events))
"outside a heal, the measured size is committed as before")))
;; The heal phases through the mounted renderer: a text is measured when it
;; mounts, and how often it mounts depends on its phase.
(def ^:private measured-text
"Stands in for `html/text-shape*`: a node to measure, with no content."
(react/forwardRef
(fn [_props ref]
(react/createElement "div" #js {:ref ref :className "measured-text"}))))
(defn- next-immediate
"Resolves after the tasks React's scheduler queued with `setImmediate`
so far have run."
[]
(js/Promise. (fn [resolve] (js/setImmediate resolve))))
(defn- mount-text-changes
"Mount `text-changes-renderer` in a jsdom document. Returns `:render`,
which renders it with a map of text shapes, `:measuring`, the number of
texts mounted to be measured, `:errors`, what React reported, and
`:unmount`, which resolves once React's scheduler has run. react-dom
reads the global `window`, so the jsdom one stays installed until then."
[]
(let [errors (atom [])
on-error (fn [error _info] (swap! errors conj error))
window (.-window (JSDOM. "<!doctype html><div id=\"root\"></div>"))
container (.getElementById (.-document window) "root")
root (rdc/createRoot container #js {:onUncaughtError on-error
:onCaughtError on-error
:onRecoverableError on-error})
previous (.-window js/globalThis)]
(set! (.-window js/globalThis) window)
{:render (fn [shapes]
(rd/flushSync
#(.render root (mf/element vth/text-changes-renderer
#js {"text-shapes" shapes}))))
:measuring #(.-length (.querySelectorAll container ".measured-text"))
:errors #(deref errors)
:unmount (fn []
(rd/flushSync #(.unmount root))
(p/finally (next-immediate)
#(set! (.-window js/globalThis) previous)))}))
(defn- with-text-changes
"Run `(f mount counts)` with `text-changes-renderer` mounted and every
text measured `height` px tall. `counts` returns the number of
measurements so far and the options of each resize request. Resolves
once `f` settles and the renderer is unmounted."
[height f]
(let [measures (atom 0)
resizes (atom [])]
(mock/with-mocks*
{tsp/calc-position-data (mock/stub (fn [_id]
(swap! measures inc)
(p/resolved [fragment])))
dom/query (mock/stub (constantly #js {}))
dom/get-bounding-rect (mock/stub (constantly {:width 200 :height height}))
dwt/resize-text (mock/stub (fn [& args]
(swap! resizes conj (last args))
(ptk/data-event ::resize {})))
dwt/update-position-data (mock/stub (fn [& _] (ptk/data-event ::position-data {})))
wrf/run-pending! (mock/stub (fn [_kind _ids f] (f)))
html/text-shape* measured-text
st/emit! (mock/stub (constantly nil))}
(let [mount (mount-text-changes)
counts (fn [] {:measures @measures :resizes @resizes})]
(await (f mount counts))
(await ((:unmount mount)))))))
(t/deftest ^:async drifted-copy-is-measured-once-to-check-and-once-to-settle
(let [copy (in-copy (text :auto-height nil))
resized (assoc copy :height 34)]
(await
(with-text-changes
34
(^:async fn [{:keys [render measuring errors]} counts]
(render (by-id copy))
(await (async/wait-for #(zero? (measuring)) "the check measurement ends"))
(t/is (= {:measures 1 :resizes [no-undo]} (counts))
"the check measures the copy once and resizes it, with no undo step")
(render (by-id resized))
(await (async/wait-for #(zero? (measuring)) "the settle measurement ends"))
(t/is (= {:measures 2 :resizes [no-undo no-undo]} (counts))
"the heal resize measures it once more, with no undo step")
(render (by-id resized))
(await (async/settle))
(t/is (= 2 (:measures (counts)))
"once settled, the copy is not measured again")
(t/is (empty? (errors))))))))
(t/deftest ^:async matching-copy-is-measured-once
(let [copy (in-copy (text :auto-height nil))]
(await
(with-text-changes
17.4
(^:async fn [{:keys [render measuring errors]} counts]
(render (by-id copy))
(await (async/wait-for #(zero? (measuring)) "the check measurement ends"))
(t/is (= {:measures 1 :resizes []} (counts))
"the check measures the copy once and leaves its size alone")
(render (by-id copy))
(await (async/settle))
(t/is (= 1 (:measures (counts)))
"once checked, the copy is not measured again")
(t/is (empty? (errors))))))))