✨ Make composable interpreter steps wait for pending work

The composable interpreter treated a step as done after a 60 ms gap
with no commits, and treated its 2 s timeout as done too. Slow sync or
reflow work could finish after the step, so a case could assert on a
half-synced file.

Each event step now waits, as the plugin waitForLayoutUpdate does,
until every pending work tracked by the reflow registry has drained:
the watcher's sync wait, the sync it starts, and layout and text
reflow. A step that does not drain within 2 s fails the test and names
the work still pending, and the next variant starts with nothing
pending.

The tests cover an edit with a deliberately slow sync, undo and redo
steps that must wait for the watcher's touch-component, translation
and derived commits, a sync that never finishes, and a restart of the
edit watchers, which must keep the undo entries of an edit the same.

Also in this commit:

- Keep page-less changes from adding a nil page. Applying a commit locally
  rebuilds the object indices of every page its changes name. Changes that touch
  no page, such as :mod-component, name none, and their nil page id was rebuilt
  too: the file data in the store gained a page under a nil key holding
  {:objects nil}. Every component touch after an edit to a main added it, and
  undo never removed it.
- Check undo and redo of every step in the composable cases. The composable
  cases tested undo only where a case asked for it, so a change generator with a
  wrong inverse, or a step that splits into several undo entries, went
  unnoticed.
- Add operations and cases to the composable component suites. The composable
  runners could edit, add, remove and move children, swap and switch, but not
  run the other component operations.
- Test component validation, repair and library asset sync.
- Add a component sync benchmark with a recorded baseline. The coming refactors
  and fixes change sync code, and a slowdown must be seen and explained in the
  commit that causes it.
- Tidy the composable suite and make its cases stricter.
- Test the component sync paths no test reached. A coverage run found sync paths
  that no test ran.
- Test variant events, token sync and switch overrides. The variant events had
  almost no frontend tests, and several switch, paste, token and restore paths
  never ran.
- Test the file and container helpers and the library events. The component
  helpers of types/file and types/container and the library events of the
  workspace had the lowest coverage left.
This commit is contained in:
alonso.torres 2026-10-10 18:30:55 +02:00
parent 61ec544881
commit 680b08dcaf
51 changed files with 8020 additions and 1635 deletions

View File

@ -48,6 +48,26 @@ For shape mutations, prefer production-path helpers such as `cls/generate-update
`thf/apply-changes` validates by default and usually gives the most useful invariant failure. Pass `:validate? false` only for intentionally malformed intermediate state.
## Validation and repair tests
`common-tests.files.repair-components-test` has one test per component error code: break a file with
the helpers (`ths/update-shape`, `thc/update-component`), assert the exact set of codes, then repair
as the backend does (validate + `cfr/repair-file` until valid, at most 10 passes, like
`app.srepl.procs.file-repair`) and assert the result. Repairs that never converge are pinned with
`tm/known-failure`. A deleted component's objects are reached with `ctkl/get-component data id true`
(`thc/get-component` skips deleted ones).
## Component sync benchmark
`common/dev/bench/component_sync.clj` times component sync on fixed-size worlds (one main into
10/100/1000 copies, 3 nesting levels, a chain of dependents, a variant switch, a library update).
Each world checks its result (how many rects end red) so it never times a no-op. Run from
`common/`: `scripts/bench-components` compares with `dev/bench/component_sync_baseline.edn` and
exits 1 when a world's lower quantile is more than 10% slower; `scripts/bench-components record`
rewrites the baseline (only on purpose, saying why). It takes about 4 minutes. Every commit that
touches sync, swap or change application runs it and quotes the table in its message. The lower
quantile is compared because the mean moves with background load (devenv watchers) and GC.
## Geometry setup caution
For geometry-sensitive tests, read `mem:common/geometry-invariants` before positioning shapes. Use geometry-preserving helpers or production change helpers rather than direct single-field edits.

View File

@ -87,28 +87,111 @@ wrapper deftest in BOTH test namespaces (or only the frontend one if it needs fr
Two pure runners (no store, JVM + CLJS):
- `core/run-variant`/`run-all`: apply nodes only (no sync, `n/undo` throws). For engine tests.
- `comp.runner/run-variant`/`run-all`: the case runner. Every comp node declares its kind via
`n/IComponentOperation` (`op-kind`: `:assembly`, `:user`, `:undo`, `:frontend-only`); the
`n/IComponentOperation` (`op-kind`: `:assembly`, `:user`, `:undo`, `:redo`, `:frontend-only`); the
runner and the interpreter's `sync-op?` dispatch on it. A NEW node MUST implement it. User ops
record their production changes (`n/record-changes`, nil when nothing changed); the runner
throws if a `:user` op records nothing or another kind records changes. After a user op the
runner syncs to a fixpoint (`ch/components-changed` + `generate-sync-file-changes`, one pass
per cascade level, like the frontend watcher) and pushes op + syncs as one undo group.
`n/undo` reverts the latest group, no re-sync. The runner validates the file (against the
`n/undo` (`(n/undo k)` for k groups) reverts the latest group and moves it to a redo stack; `n/redo` applies it again
(interpreter: `dwu/redo`); neither re-syncs. A user op that pushes a group empties the redo
stack; one that changed nothing keeps it. The runner validates the file (against the
situation's files) once settled: after the sync fixpoint and after an undo group; never
between cascade passes, where an outer copy still points at the component its main dropped
(`:component-id-mismatch`), nor with `{:sync? false}`. Assembly ops (create/instantiate/nest/variant
container): no sync, no undo group. `ResetCopyInstance` is a user op here (sync + undo),
unlike the interpreter (file install). `{:sync? false}` disables sync. `Rotate`/`ChangeHeight`
container): no sync, no undo group. `n/reset` (`reset-copy-instance` resets a lineage's latest copy) is a user op (sync +
undo); the interpreter sends `dwl/reset-component`. `{:sync? false}` disables sync. `Rotate`/`ChangeHeight`/`MoveShape`
are `:frontend-only` and throw `::runner/frontend-only` (the placement step is frontend code). Swap and switch nodes use the production
`clv/generate-component-swap-in-place` (+ `clv/find-switch-target` for switch), the same code the
frontend events call. Not modelled: the `:modified-at` bump, and the swap/switch event follow-ups
(token propagation, WASM text resize, layout update). Tests:
`common-tests.logic.composable-runner-test`.
- Undo/redo round trip (`comp/undo_check.cljc`, alias `uc`), on by default in the pure runner
(`:undo-check?`): after each `:user` step that pushed a group, undo must give back the
normalized file before it and redo the file after it (the variant continues from the redone
file); a user step that pushed nothing must change nothing (`:no-undo-entry`); at the end,
undo back to the last assembly step (the baseline; a case's own undo below it moves it) and
redo all. Files compare through `app.common.test-helpers.normalize` (`thn/normalize-file`:
drops file/component `:modified-at`, optionally `:position-data`; shapes as plain maps).
Failures are recorded in the situation with labelled diffs (labels die with the variant, so
they are resolved when recorded) and a `:signature`, the set of what differs
(`uc/signature`: `[:object <label> attr]`, `:missing`/`:extra`, `:page`/`:component` alike,
`[:undo-index n]`, `[:error]`; unlabelled shapes are `:unlabelled`); `uc/check!` asserts after
the asserter and prints the signature. A case map's `:undo-check` takes `{:off "reason"}` or
`{:known-failures [{:bug "F41" :fails {phase signature} :op <the case's node> :runners
#{:pure :frontend} :when pred}]}`: strict expected failures. A mark applies to variants of its
runners (`uc/with-runner`) where its `:op` ran and `:when` holds; it covers a failure only
when the signature is exactly the pinned one, and a pinned phase that does not fail as pinned
fails the case. Marks without `:fails` throw. Never edit a pin to make a case pass: a pin
changes only when the failure is understood, and the mark goes only in the fix commit. The interpreter runs the same round trip on every `:user` and
`:frontend-only` event step through the real `dwu/undo`/`dwu/redo`, and also checks the
workspace undo index (`:undo-index`/`:redo-index` phases): a step must add exactly one undo
entry or group. File installs (assembly ops) are its baselines; a skipped optional and an inline `Test` are not. The interpreter
empties `:workspace-undo` per variant. Frontend snapshots drop `:position-data` under WASM.
Undo groups get lost in derived work: `initialize-shape-layout` buffers `:layout/update`
without its `:undo-group` (F43), so a swap's reflow lands in entries of its own. Match
steps by node identity, never by record type or rendered name: `n/MoveChild` does not resolve
through an alias on the JVM, and the JS test build strips record names (transcripts show
`node`).
- The interpreter records an event op's application as the op's own fields, not what its
`apply-to` would record, so an accessor that must work in both runners reads the file
structure (e.g. `level-rect`, `n/deleted-component-id`), never the node's recorded data.
Shapes off the current page: `tm/find-shape`, `tm/role-shape-in-file` (setup
`simple-component-with-copies-on-two-pages`). When an accessor needs what an op created
(e.g. the duplicate's head), the node implements `n/IAppliedResult` (read from the file
before and after); the pure node and the interpreter's `record-op` both record it.
- `n/create-component` builds 0.01-sized frames unless given `:size`. The transform math
writes float noise into those sizes, so frontend syncs emit reflows whose commits lose
their undo group (F43) at timing-dependent points (`initialize-shape-layout` buffers
`:layout/update` in 100 ms windows): undo pins over such reflows are nondeterministic.
New cases that are not about geometry pass `:size` (nesting sizes the outer frames too).
F43 from float noise lives in case AJ only (frontend only, round trip off): it pins the
value one undo leaves, which does not depend on how many entries the reflow makes. Case AN
pins F43 from a real reflow (a flex main's margin edit, synced): stable in repeated runs.
- Case assertions a known bug breaks use `tm/known-failure bug expected pinned actual`: a
strict expected failure at assertion level (passes only while `actual` is the pinned wrong
value). The undo-check marks cover only round-trip failures.
- Text: `n/edit-text` (`:text`/`:font-size` of the first span) with `n/text-edit-commit`, which
includes the editor's automatic rename when the name was generated from the old content;
setup `simple-text-component-with-copy` (text named after its content).
- The interpreter unwraps nested choices (`(tm/optional (tm/one-of …))`); `(optional
(in-sequence …))` is still not flattened.
- Depth sweeps: `depth-sweep` in `cases.cljc`, a one-of over skip,
`(n/make-nested-component name)` and `(n/make-nested-component name 2)`; asserters read
`n/nesting-depth`. Two independent nesting optionals run depth 1 twice.
- General target-based nodes: `n/swap-shape target to` (`to` a lineage name or a component label), `n/move-to-cell board child row column`, `n/reset target` (`dwl/reset-component` in the interpreter). `n/swap-component name level to` is `swap-shape` on `n/nested-head-of`. `n/nested-head-in name` (and the general `n/nested-head-under parent-target`) finds a copy's nested
head through its parent, so it survives swaps and switches (they keep the head id anyway).
Careful: `n/lineage-component-id` is the OUTER component after nesting.
- Variant properties: `n/add-variant-property`, `remove-`, `rename-`, `reorder-variant-properties`
and `set-variant-property-value` are one node (`EditVariantProperty`); `n/variant-property-call`
resolves the edit to the arguments both the `clvp/generate-*` generator and the `dwv/*` event take.
A member is named by the value it was built with; read its current state from the file
(`n/member-properties`, `n/member-component`, `n/member-root`). `n/switch-variant` takes `:pos`
(a number or a `(situation -> pos)` fn) for sets with several properties.
`n/add-variant set member` duplicates a member (`clv/generate-add-new-variant`; `dwv/add-new-variant`,
whose delayed DOM focus `check` neutralises by stubbing `dom/get-element`); ask the node for the
new component (`n/added-variant-component-id`).
Frontend-only variant actions are one node, `n/VariantAction` (`n/transform-in-variant`,
`combine-as-variants`, `rename-variant`, `rename-variant-in-layers`, `remove-empty-properties`,
`set-variant-error`, `variant-shortcut`); the interpreter's `variant-action-events` sends them.
A set they build has no `variant-set` record: read it with `n/component-of` and
`n/variant-component-ids`; `switch-variant` takes the value as a fn for it.
- Tokens: `n/add-tokens` (assembly: an active set of border radius tokens), `n/apply-token`,
`n/unapply-token`, check `n/has-token?`. The interpreter sends `dwta/apply-token`, which resolves
tokens asynchronously and opens no pending work (F54), so `await-step` takes a `ready?` predicate
(`op-ready`: the token shows on the shape) that must hold before it awaits the pending work.
- `n/paste-to-root target`: the clipboard's copy (shape-refs of nested heads advanced, the skipped ref
chain's touched merged) and paste at the root; the interpreter pastes `thp/simulate-copy-shape`'s data.
That helper mirrors `copy-selected`'s advance; keep them in step. A duplicate inside a copy is
refused by `ctk/allow-duplicate?`, and an alt-duplication with no move makes the next edit join
its undo group (it expects the drag's move), so neither models a move out of a main.
- `n/undo-before-sync` (frontend-only) emits an edit and `dwu/undo` in one step, so the undo
commits while the watcher still holds the edit's sync.
- Label map gotcha: running a second variant re-registers labels, so assert on a situation
before running the next one (`thi/id` then points at the new run's shapes). Case letters B..O;
before running the next one (`thi/id` then points at the new run's shapes). Case letters B..Z, then AA..;
the sweeps (K: depth × edit-precedence; L: swaps; M: variant switches; N: rotated-instance
geometry, on the #10109 fix branch until merged; O: switch of an overridden copy, mains
agreeing or not) are the flagship pattern — read them before
agreeing or not; Q: detach at depth 0..2, nested copies stay linked; R: update-main at depth 0..2 with two copies; S: delete/restore with a copy on another page; T: duplicate a copy at depth 0..2; U: move a copy into a main with a copy; V: new edit after undo empties redo; W: `(n/undo 3)` over nested cascades; X: undo before the edit's sync, frontend only; AJ: F43, one undo after a nested sync reverts only the reflow, frontend only; Y: text override × main text change, per subgroup; Z: main child move, frontend only; AA..AE: swap outcomes asserted on values, not slot storage, so they survive the Phase 2b swap model; AF: grid cell move vs a swapped copy child, setup `grid-component-with-copy`; AG/AH/AI: ports of the plugin's slot-alignment cases, setup `component-with-sibling-instances`, check `setup/misaligned-sub-heads`; AK: update main into a grid main, F49 pinned; AL: update main renames the component (`change-property` takes `:name`); AM: update main of a swap inside a group, setup `grouped-component-with-copy`, F16 pinned; AN: flex child margin override through main edit, reset and update main, setup `flex-component-with-copy`; `change-property` takes `:margin`, which the interpreter sends as `dwsl/update-layout-child`; AO: a copy dropped into a grid cell of a main (`nest-copy` with `:cell`, sent as `dwt/move-shapes-to-frame`), F41 pinned; AP: a library main's middle child removal reaches a copy in another file (in one file, deleting a main child deletes the copies' children itself, so sync never meets the copy child), setup `cross-file-component-with-many-children`; AQ: main change reaches a copy nested in a sub-board, setup `component-nested-in-a-sub-board`; AR: variant property edits keep a member's copies as they are, then a switch finds its member by the edited properties; AS: an added variant joins the set and is a switch target; AT..AX, frontend only: transform into a variant, combine, rename a variant (F6 pinned: the transaction keeps the container commit's undo group, the copies' sync takes the main renames'), rename in layers + remove empty properties + member error, the shortcuts that add members; AY: a border radius token on a main reaches untouched copies and its removal too, F55 pinned; AZ: a nested copy pasted out of its main keeps the main's overrides) are the flagship pattern — read them before
writing a new sweep.
**Scenario lineage model** (behind the sweeps): scenario ops track named component lineages as
@ -123,13 +206,21 @@ nestings do not propagate between each other.
**Interpreter:** installs the situation's files into the global `st/state` (aux files tagged
`:library-of`), starts the production watchers the app starts — `dw/initialize-edit-watchers`
(undo stack, layout, text reflow, WASM text measurement; stopped by `dw/finalize-edit-watchers`)
and `dwl/watch-library-changes` (component + token watchers) — then maps
event-ops to REAL workspace events (`dwsh/update-shapes`, `dwl/component-swap`,
(undo stack, layout, text reflow, WASM text measurement; stopped by `dw/finalize-edit-watchers`,
replaced when started again) and `dwl/watch-library-changes` (component + token watchers;
replaced when started again) — then maps
event-ops to REAL workspace events (`dwsh/update-shapes`, `dwl/component-swap` (also `n/swap-shape`, any copy head),
`dwv/variants-switch`, `dwt/increase-rotation` — which runs the `check-delta` placement
classification — `dwt/update-dimensions`, `dwu/undo`, `dwl/sync-file`, …) and runs sync-ops'
`apply-to` against the live store file; awaits settlement (idle-gap heuristic + per-op grace) and
re-reads `:file` each step so the shared accessors keep working.
classification — `dwt/update-dimensions`, `dwl/detach-component`, `dwl/update-component-sync`, `dwl/delete-component`, `dwl/restore-component`, `dws/duplicate-shapes`, `dwsh/relocate-shapes` (nest-copy), `dwtx/v2-update-text-shape-content` (edit-text, the editor's on-blur commit with its automatic rename), `dwu/undo`, `dwl/sync-file`, …) and runs sync-ops'
`apply-to` against the live store file; each event step goes through `ftm/await-step`, which
resolves once `wrf/settled nil` (the watcher's `:sync-file` wait, opened for EVERY local commit,
plus the sync and layout/text reflow it starts) or reports `{:timeout pending}` after 2s; a
timed-out step fails the test and skips the asserter. Contract: producers must open their
pending work synchronously while the events are processed (Potok processes sub-events
synchronously); an async hop without a pending task makes steps resolve early. Tests:
`frontend-tests.composable-tests.completion-contract-test` (slowed-down sync via a mocked
`dwl/sync-file`), `frontend-tests.data.workspace-sync-barrier-test`. Re-reads `:file` each step
so the shared accessors keep working.
STORE-SWAP IMMUNITY: other test namespaces `set!` `st/state`/`st/stream` and never restore, while
the `app.main.refs` lenses stay bound to the ORIGINAL atoms — propagation then dies silently. The
interpreter captures the atoms at namespace-load time and re-`set!`s them per variant.
@ -143,11 +234,14 @@ Running (frontend): `cd frontend && pnpm run build:test`, then
persistence, no viewport. Edit-reacting subscriptions come from the shared events above; a NEW
edit-reacting subscription belongs inside `initialize-edit-watchers` (or
`watch-library-changes`), never wired inline in `initialize-workspace`, or the harness silently
misses it. Headless there is no DOM text measurement, so `:text/reflow` work never drains.
misses it. Headless there is no DOM text measurement: `install!` starts
`headless-text-measurement`, a stand-in that opens and closes a `:text-measure` task for each
`:text/reflow` (geometry and `:position-data` unchanged), so text steps settle. It does not
reproduce what the real measurement commits (F37: `commit-position-data`).
**Caveats:** inline `Test` exceptions are UNCAUGHT on the frontend (crash the runner — assert in
the trailing asserter). `(optional (in-sequence …))` is not flattened for the interpreter — use
independent optionals. The Serena/clj-kondo cache for `nodes.cljc` goes stale (phantom symbols) —
independent optionals (nested choices are fine). The Serena/clj-kondo cache for `nodes.cljc` goes stale (phantom symbols) —
trust the build. Cross-namespace global-state leaks land in this suite first; suspect them before
the framework on inexplicable full-run-only failures. Case H's `sync-file` schedules a delayed RPC
that fails headless (benign; absorbed by per-op grace).
@ -178,6 +272,14 @@ Distinguishing abstractions (the OOP articulation of the shared principles):
(CI adapter) are three thin consumers.
- Cases live in `src/composable-tests/cases/` as `case<Identifier>.ts` (e.g. `MainEditSyncs` — the
sweep that found #10109).
- Roles are bound BY NAME in the situation: two foundation ops with the same role names overwrite
each other. `OpCreateNestableComponent(strategy, name)` prefixes its roles with `name`; give
every extra lineage in a case a name.
- `OpDetach`/`OpSwap`/`OpReset` wait for pending propagation before acting (a script could
otherwise act inside the sync window, which no user can). `swapComponent` keeps touched (F33).
The suite pins published `@penpot/plugin-types` 1.4.2, which lacks `resetOverrides` (typed cast).
- Known bugs: `Assert.knownFailure(bug, expected, pinned, actual, equals)` (same order as `tm/known-failure`), the counterpart of
`tm/known-failure`.
- Panel checkboxes carry stable DOM ids (case identifier / `Identifier-N` composites) for remote
control via Playwright; recipe in the README.

View File

@ -0,0 +1,313 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns bench.component-sync
"Benchmark of component sync on fixed-size worlds, with a recorded
baseline to compare against.
Each world is built once; only the work a user edit causes is timed: the
sync of the changed components, then of the components each sync changed,
until none is left (the frontend watcher does one pass per sync commit),
with every change applied to the file.
Run from `common/` with `scripts/bench-components` (`record` writes the
baseline, `compare`, the default, checks against it)."
(:require
[app.common.files.changes-builder :as pcb]
[app.common.logic.libraries :as cll]
[app.common.logic.shapes :as cls]
[app.common.logic.variants :as clv]
[app.common.test-helpers.components :as thc]
[app.common.test-helpers.composable.comp.runner :as r]
[app.common.test-helpers.compositions :as tho]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[app.common.test-helpers.variants :as thv]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.pprint :as pp]
[clojure.string :as str]
[criterium.core :as cri]))
(def ^:private baseline-path "dev/bench/component_sync_baseline.edn")
;; A world slower than its baseline by more than this ratio is flagged.
(def ^:private tolerance 1.10)
(def ^:private bench-opts
{:samples 20
:target-execution-time (* 500 1000 1000)
:warmup-jit-period (* 3 1000 1000 1000)})
;; How long each world runs untimed before any is measured, in ms, so the
;; code they share is compiled before the first measurement.
(def ^:private warmup-ms 3000)
;; ---- Sync
(defn- apply-changes
[file changes]
(thf/apply-changes file changes :validate? false))
(defn- edit
"`file` after `f` changed the shape `label` through the production path,
and the ids of the components that changed."
[file label f]
(let [page (thf/current-page file)
changes (cls/generate-update-shapes (pcb/empty-changes nil (:id page))
#{(thi/id label)}
f
(:objects page)
{})]
[(apply-changes file changes) (r/changed-components (:data file) changes)]))
(defn- sync-cascade
"`[file passes]` after syncing the copies of `component-ids` in `file` to
a fixpoint (see `r/sync-cascade`)."
[file libraries component-ids]
(let [{:keys [file passes]} (r/sync-cascade file libraries component-ids)]
[file passes]))
(defn- red
[shape]
(assoc shape :fills (ths/sample-fills-color :fill-color "#ff0000")))
;; ---- Worlds
;;
;; A world is `{:key :describe :run :reds}`; `run` is the timed work, a
;; function of no arguments returning `[file passes]`, and `reds` how many
;; rects the resulting file must have red, so a world that synced nothing
;; fails instead of timing nothing.
(defn- red-rects
[file]
(->> (vals (:objects (thf/current-page file)))
(filter #(and (= :rect (:type %))
(= "#ff0000" (-> % :fills first :fill-color))))
(count)))
(defn- instantiate-many
"`file` with `n` copies of the component `label`, labelled `prefix-<i>`."
[file label prefix n & {:as params}]
(reduce (fn [file i]
(thc/instantiate-component file label (keyword (str prefix "-" i)) params))
file
(range n)))
(defn- nest
"`file` with a new component `label`, whose main `root-label` holds a copy
of the component `inner-label`."
[file label root-label inner-label]
(-> file
(tho/add-frame root-label)
(thc/instantiate-component inner-label (keyword (str (name root-label) "-inner"))
:parent-label root-label)
(thc/make-component label root-label)))
(defn- main-edit-into-copies
"One main whose child changes, synced into `n` copies."
[n]
(let [[file ids] (-> (thf/sample-file :file1)
(tho/add-simple-component :c0 :root0 :child0)
(instantiate-many :c0 "copy" n)
(edit :child0 red))]
{:key (keyword (str "main-edit-into-" n "-copies"))
:describe (str "a main child changes; " n " copies sync")
:run #(sync-cascade file {} ids)
:reds (inc n)}))
(defn- deepest-edit-through-three-levels
"Components c1 ⊃ c0, c2 ⊃ c1, c3 ⊃ c2, 100 copies of c3; c0's child
changes."
[]
(let [[file ids] (-> (thf/sample-file :file1)
(tho/add-simple-component :c0 :root0 :child0)
(nest :c1 :root1 :c0)
(nest :c2 :root2 :c1)
(nest :c3 :root3 :c2)
(instantiate-many :c3 "copy" 100)
(edit :child0 red))]
{:key :deepest-edit-through-three-levels
:describe "the deepest of 3 nesting levels changes; 100 copies of the top sync"
:run #(sync-cascade file {} ids)
;; the main, its images in the three outer mains, and the copies
:reds 104}))
(defn- edit-through-a-chain-of-dependents
"Components a, b ⊃ a, c ⊃ b, with 100 copies of each; a's child changes."
[]
(let [[file ids] (-> (thf/sample-file :file1)
(tho/add-simple-component :a :root-a :child-a)
(nest :b :root-b :a)
(nest :c :root-c :b)
(instantiate-many :a "copy-a" 100)
(instantiate-many :b "copy-b" 100)
(instantiate-many :c "copy-c" 100)
(edit :child-a red))]
{:key :edit-through-a-chain-of-dependents
:describe "a changes in the chain a ⊂ b ⊂ c; 100 copies of each sync"
:run #(sync-cascade file {} ids)
;; the main, its images in b and c, and the copies
:reds 303}))
(defn- variant-switch-into-copies
"A component whose main holds a copy of variant member v1, with 100 copies;
the copy in the main switches to member v2."
[]
(let [file (-> (thf/sample-file :file1)
(thv/add-variant-with-child :vset :v1 :v1-root :v2 :v2-root :v1-child :v2-child
:child2-params {:fills (ths/sample-fills-color :fill-color "#ff0000")})
(nest :t :root-t :v1)
(instantiate-many :t "copy" 100))
page (thf/current-page file)
shape (ths/get-shape file :root-t-inner)
libs {(:id file) file}
target (clv/find-switch-target libs shape 0 "Value2")
switch (fn []
(let [[_ changes _] (clv/generate-component-swap-in-place
(pcb/empty-changes nil (:id page))
page libs (:data file) shape (:id target) true)]
(sync-cascade (apply-changes file changes)
{}
(r/changed-components (:data file) changes))))]
{:key :variant-switch-into-copies
:describe "a variant copy in a main switches; 100 copies of the main sync"
:run switch
;; member v2's rect, the switched copy in the main, and the copies
:reds 102}))
(defn- library-update-into-copies
"A library component with 500 copies in a consuming file; the library main
changed and the file accepts the update."
[]
(let [library (-> (thf/sample-file :library :is-shared true)
(tho/add-simple-component :lc :lroot :lchild))
file (-> (thf/sample-file :file1)
(instantiate-many :lc "copy" 500 :library library))
[library _] (edit library :lchild red)
libraries {(:id library) library (:id file) file}
update (fn []
(let [changes (cll/generate-sync-file-changes (pcb/empty-changes)
nil
:components
(:id file)
nil
(:id library)
libraries
(:id file))]
[(apply-changes file changes) 1]))]
{:key :library-update-into-copies
:describe "a library main changed; a file with 500 copies updates"
:run update
:reds 500}))
(defn- worlds
[]
[(main-edit-into-copies 10)
(main-edit-into-copies 100)
(main-edit-into-copies 1000)
(deepest-edit-through-three-levels)
(edit-through-a-chain-of-dependents)
(variant-switch-into-copies)
(library-update-into-copies)])
;; ---- Measuring
(defn- ms
[seconds]
(/ (Math/round (* seconds 1e6)) 1e3))
(defn- measure
[{:keys [key describe run reds]}]
(println (str " " (name key) ": " describe))
(let [[file passes] (run)
_ (when-not (= reds (red-rects file))
(throw (ex-info (str (name key) " did not sync: " (red-rects file)
" red rects, expected " reds)
{:world key})))
result (cri/benchmark* run bench-opts)]
[key {:mean-ms (ms (first (:mean result)))
:lower-q-ms (ms (first (:lower-q result)))
:passes passes}]))
(defn- warm-up!
[worlds]
(doseq [{:keys [run]} worlds]
(let [end (+ (System/currentTimeMillis) warmup-ms)]
(while (< (System/currentTimeMillis) end)
(run)))))
(defn- run-all
[]
(let [worlds (worlds)]
(println " warming up")
(warm-up! worlds)
(into (sorted-map) (map measure) worlds)))
(defn- sh-out
[& args]
(try
(let [{:keys [exit out]} (apply shell/sh args)]
(when (zero? exit) (str/trim out)))
(catch Exception _ nil)))
(defn- machine
[]
{:cpu (some-> (sh-out "sh" "-c" "grep -m1 'model name' /proc/cpuinfo | cut -d: -f2")
(str/trim))
:cores (.availableProcessors (Runtime/getRuntime))
:os (str (System/getProperty "os.name") " " (System/getProperty "os.arch"))
:jvm (System/getProperty "java.version")})
(defn- record!
[results]
(let [baseline {:commit (or (sh-out "git" "rev-parse" "--short" "HEAD") "unknown")
:date (str (java.time.LocalDate/now))
:machine (machine)
:results results}]
(with-open [w (io/writer baseline-path)]
(binding [*out* w]
(println ";; Component sync benchmark baseline, written by `scripts/bench-components record`.")
(pp/pprint baseline)))
(println "Baseline written to" baseline-path)
true))
(defn- compare!
"Print each world's time against the baseline. Returns false when a world
is slower than its baseline by more than the tolerance. The lower
quantile is compared: background load and GC pauses move it far less
than the mean."
[results]
(let [{:keys [commit] recorded :machine :as baseline} (edn/read-string (slurp baseline-path))
rows (for [[key {:keys [lower-q-ms mean-ms]}] results
:let [base (get-in baseline [:results key :lower-q-ms])
ratio (when base (/ lower-q-ms base))]]
{:world (name key)
:baseline base
:now lower-q-ms
:mean mean-ms
:ratio (some-> ratio (* 100) Math/round (/ 100.0))
:flag (cond (nil? ratio) "new"
(> ratio tolerance) "SLOWER"
:else "")})]
(println "Baseline from commit" commit "on" (:cpu recorded))
(when (not= recorded (machine))
(println "Warning: the baseline was recorded on another machine or JVM; ratios are rough."))
(println "Times are the lower quantile (2.5%) of each world, in ms.")
(pp/print-table [:world :baseline :now :mean :ratio :flag] rows)
(not-any? #(= "SLOWER" (:flag %)) rows)))
(defn -main
[& [mode]]
(println "Component sync benchmark")
(let [results (run-all)
ok? (case (or mode "compare")
"record" (record! results)
"compare" (compare! results))]
(shutdown-agents)
(System/exit (if ok? 0 1))))

View File

@ -0,0 +1,23 @@
;; Component sync benchmark baseline, written by `scripts/bench-components record`.
{:commit "1e6615a132",
:date "2026-10-09",
:machine
{:cpu "Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz",
:cores 12,
:os "Linux amd64",
:jvm "26.0.2"},
:results
{:deepest-edit-through-three-levels
{:mean-ms 36.343, :lower-q-ms 35.215, :passes 4},
:edit-through-a-chain-of-dependents
{:mean-ms 75.119, :lower-q-ms 68.931, :passes 3},
:library-update-into-copies
{:mean-ms 89.295, :lower-q-ms 83.083, :passes 1},
:main-edit-into-10-copies
{:mean-ms 1.847, :lower-q-ms 1.79, :passes 1},
:main-edit-into-100-copies
{:mean-ms 16.234, :lower-q-ms 15.415, :passes 1},
:main-edit-into-1000-copies
{:mean-ms 158.728, :lower-q-ms 153.086, :passes 1},
:variant-switch-into-copies
{:mean-ms 33.1, :lower-q-ms 32.052, :passes 1}}}

View File

@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Runs the component sync benchmark (`dev/bench/component_sync.clj`).
# scripts/bench-components compare against the recorded baseline
# scripts/bench-components record record a new baseline
# Exits 1 when a world is more than 10% slower than its baseline.
set -euo pipefail
cd "$(dirname "$0")/.."
exec clojure -M:dev -m bench.component-sync "${1:-compare}"

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -14,13 +14,18 @@
`ch/components-changed` reports, then the components each sync changed,
until none is left. The frontend component watcher does the same, one
pass per sync commit.
- Undo. A user operation and the syncs it caused form one undo group.
`n/undo` reverts the latest group and syncs nothing, as in the frontend,
where an undo commit only bumps the component's `:modified-at`.
- Undo and redo. A user operation and the syncs it caused form one undo
group. `n/undo` reverts the latest groups and `n/redo` applies again the
latest reverted one; neither syncs, as in the frontend, where an undo
or redo commit only bumps the component's `:modified-at`. A user
operation that pushes a group empties the redo stack.
Assembly operations (create, instantiate, nest) change the file with no sync
and no undo group, like the frontend interpreter's file installs.
Every variant also runs the undo/redo round trip of
`app.common.test-helpers.composable.comp.undo-check`.
Operations whose result needs frontend code (kind `:frontend-only`) are
rejected. Not modelled: the `:modified-at` bump of a changed component,
and the frontend follow-ups of a swap or switch (token propagation, WASM
@ -30,6 +35,7 @@
[app.common.files.changes-builder :as pcb]
[app.common.logic.libraries :as cll]
[app.common.test-helpers.composable.comp.nodes :as n]
[app.common.test-helpers.composable.comp.undo-check :as uc]
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.files :as thf]))
@ -39,7 +45,7 @@
;; A guard against a sync cascade that never settles.
(def ^:private max-sync-passes 100)
(defn- changed-components
(defn changed-components
"Ids of the components whose main `changes` modified, judged against
`old-data`, the file data before `changes` applied."
[old-data changes]
@ -62,33 +68,21 @@
(thf/validate-file! file (libraries situation file))
situation))
(defn- component-sync-changes
"The changes that sync the copies of `component-id` in `file`, as the
frontend `sync-file` event builds them for a local component."
[situation file component-id]
(let [file-id (:id file)]
(cll/generate-sync-file-changes (pcb/empty-changes)
nil
:components
file-id
component-id
file-id
(libraries situation file)
file-id)))
(defn- sync-file
"Sync `situation`'s file, starting from the components that `changes`
modified (judged against `old-data`), until no component is left to sync,
and validate the result. Returns `[situation syncs]`, with `syncs` the
applied sync changes in order."
[situation old-data changes]
(loop [file (tm/file situation)
pending (vec (changed-components old-data changes))
(defn sync-cascade
"Sync the copies of `component-ids` in `file`, then those of the components
each sync changed, until none is left, as the frontend `sync-file` event
builds the changes for a local component; the frontend watcher runs one
pass per sync commit. `libraries` are the other files by id. Returns
`{:file :syncs :passes}`, with `syncs` the sync changes that changed
something, in order."
[file libraries component-ids]
(loop [file file
pending (vec component-ids)
syncs []
passes 0]
(cond
(empty? pending)
[(validate-settled! (tm/with-file situation file)) syncs]
{:file file :syncs syncs :passes passes}
(>= passes max-sync-passes)
(throw (ex-info "Component sync did not settle"
@ -97,42 +91,102 @@
:passes passes}))
:else
(let [component-id (first pending)
sync (component-sync-changes situation file component-id)
file' (thf/apply-changes file sync :validate? false)
more (->> (changed-components (:data file) sync)
(remove (set pending)))]
(let [file-id (:id file)
sync (cll/generate-sync-file-changes (pcb/empty-changes)
nil
:components
file-id
(first pending)
file-id
(assoc libraries file-id file)
file-id)
file' (thf/apply-changes file sync :validate? false)
more (->> (changed-components (:data file) sync)
(remove (set pending)))]
(recur file'
(into (subvec pending 1) more)
(cond-> syncs (seq (:redo-changes sync)) (conj sync))
(inc passes))))))
(defn- sync-file
"Sync `situation`'s file, starting from the components that `changes`
modified (judged against `old-data`), and validate the result. Returns
`[situation syncs]`, with `syncs` the applied sync changes in order."
[situation old-data changes]
(let [{:keys [file syncs]} (sync-cascade (tm/file situation)
(tm/aux-files situation)
(changed-components old-data changes))]
[(validate-settled! (tm/with-file situation file)) syncs]))
(defn- push-undo-group
"Add `group`, the changes of one user operation and its syncs in order, to
the undo stack. Changes with nothing to undo are left out, as the frontend
undo stack leaves out commits with no undo changes."
the undo stack and empty the redo stack. Changes with nothing to undo are
left out, as the frontend undo stack leaves out commits with no undo
changes; a group left empty changes neither stack."
[situation group]
(let [group (filterv (comp seq :undo-changes) group)]
(cond-> situation
(seq group) (update ::undo-stack (fnil conj []) group))))
(seq group) (-> (update ::undo-stack (fnil conj []) group)
(assoc ::redo-stack [])))))
(defn- run-undo
"Revert the latest undo group, newest changes first, and validate the
result. With an empty stack it changes nothing, like the frontend undo."
[situation op]
(let [stack (get situation ::undo-stack [])
group (peek stack)
file (reduce (fn [file changes]
(thf/apply-changes file
{:redo-changes (:undo-changes changes)}
:validate? false))
(tm/file situation)
(rseq (or group [])))]
(defn- apply-group
"Apply to the situation's file the `side` changes (`:undo-changes` or
`:redo-changes`) of each changes in `group`, in order, and validate the
result."
[situation side group]
(let [file (reduce (fn [file changes]
(thf/apply-changes file
{:redo-changes (get changes side)}
:validate? false))
(tm/file situation)
group)]
(-> situation
(tm/with-file file)
(validate-settled!)
(assoc ::undo-stack (if (seq stack) (pop stack) stack))
(tm/record-application op {:undone (count group)}))))
(validate-settled!))))
(defn- move-group
"Move the latest group of the `from` stack to the `to` stack, applying its
`side` changes, in `order` (`seq` or `rseq`). Returns `[situation group]`;
with an empty `from` stack it changes nothing, like the frontend undo and
redo."
[situation from to side order]
(let [stack (get situation from [])]
(if (empty? stack)
[situation nil]
(let [group (peek stack)]
[(-> situation
(apply-group side (order group))
(assoc from (pop stack))
(update to (fnil conj []) group))
group]))))
(defn- undo-group
"Revert the latest undo group, newest changes first, and move it to the
redo stack."
[situation]
(move-group situation ::undo-stack ::redo-stack :undo-changes rseq))
(defn- redo-group
"Apply again the latest redo group, oldest changes first, and move it back
to the undo stack."
[situation]
(move-group situation ::redo-stack ::undo-stack :redo-changes seq))
(defn- run-undo
"Undo the latest `(:times op)` groups, one at a time."
[situation op]
(let [[situation undone]
(reduce (fn [[situation undone] _]
(let [[situation group] (undo-group situation)]
[situation (+ undone (count group))]))
[situation 0]
(range (:times op)))]
(tm/record-application situation op {:undone undone})))
(defn- run-redo
[situation op]
(let [[situation group] (redo-group situation)]
(tm/record-application situation op {:redone (count group)})))
(defn- op-kind
"The kind of a leaf operation (see `n/IComponentOperation`), or nil for an
@ -159,19 +213,89 @@
:op op
:kind kind}))))
(defn undo-depth
"How many undo groups the runner holds in `situation`."
[situation]
(count (get situation ::undo-stack)))
(defn redo-depth
"How many redo groups the runner holds in `situation`."
[situation]
(count (get situation ::redo-stack)))
(defn- snapshot
[situation]
(uc/snapshot (tm/file situation)))
(defn- try-round-trip
"Run `round-trip` (situation -> situation) on `situation`. When it throws,
record the error as a failure of `phase` at `step` and return `situation`
unchanged."
[situation step phase round-trip]
(try
(round-trip situation)
(catch #?(:clj Exception :cljs :default) e
(uc/add-error situation step phase (str (ex-message e) " " (pr-str (ex-data e)))))))
(defn- check-step
"The round trip of user step `op` (see `uc`): `before` is the normalized
file before it and `depth` the undo depth before it."
[situation op before depth]
(let [step (uc/step situation op)
after (snapshot situation)]
(if (= depth (undo-depth situation))
(uc/compare-states situation step :no-undo-entry before after)
(try-round-trip
situation step :undo
(fn [situation]
(let [undone (first (undo-group situation))
undone (uc/compare-states undone step :undo before (snapshot undone))
redone (first (redo-group undone))]
(uc/compare-states redone step :redo after (snapshot redone))))))))
(defn- check-variant
"The end-of-variant round trip (see `uc`): undo back to the baseline, then
redo all."
[situation]
(let [{:keys [depth] :as baseline} (uc/baseline situation)
times (- (undo-depth situation) depth)
final (snapshot situation)]
(if (pos? times)
(try-round-trip
situation nil :variant-undo
(fn [situation]
(let [undone (nth (iterate (comp first undo-group) situation) times)
undone (uc/compare-states undone nil :variant-undo
(:snapshot baseline) (snapshot undone))
redone (nth (iterate (comp first redo-group) undone) times)]
(uc/compare-states redone nil :variant-redo final (snapshot redone)))))
situation)))
(defn- mark-baseline
[situation]
(uc/mark-baseline situation (undo-depth situation) (snapshot situation)))
(defn- run-node
"Apply one leaf operation of `kind`. A user operation is followed by its sync
(when `:sync?`) and pushes its undo group."
[situation op kind {:keys [sync?]}]
(when `:sync?`), pushes its undo group, and gets its round trip (when
`:undo-check?`). An assembly operation moves the round trip's baseline."
[situation op kind {:keys [sync? undo-check?]}]
(let [old-data (:data (tm/file situation))
before (when undo-check? (snapshot situation))
depth (undo-depth situation)
[recorded? changes situation] (n/take-changes (tm/apply-to op situation))]
(check-recorded-changes! op kind recorded?)
(if (nil? changes)
situation
(let [[situation syncs] (if sync?
(sync-file situation old-data changes)
[situation []])]
(push-undo-group situation (into [changes] syncs))))))
(cond-> (if (nil? changes)
situation
(let [[situation syncs] (if sync?
(sync-file situation old-data changes)
[situation []])]
(push-undo-group situation (into [changes] syncs))))
(and undo-check? (= kind :user))
(check-step op before depth)
(and undo-check? (= kind :assembly))
(mark-baseline))))
(defn- run-op
[situation op opts]
@ -187,7 +311,15 @@
(let [kind (op-kind op)]
(case kind
:undo
(run-undo situation op)
(let [situation (run-undo situation op)]
;; never undo past the state a case's own undo went back to
(cond-> situation
(and (:undo-check? opts)
(< (undo-depth situation) (:depth (uc/baseline situation))))
(mark-baseline)))
:redo
(run-redo situation op)
:frontend-only
(throw (ex-info (str "The pure runner cannot run " (pr-str (type op))
@ -198,19 +330,27 @@
(run-node situation op kind opts)))))
(defn undo-depth
"How many undo groups the runner holds in `situation`."
[situation]
(count (get situation ::undo-stack)))
(defn run-variant
"Run one concrete (already enumerated) variant: build a fresh situation with
`setup` and run `operation` with sync and undo, returning the resulting
situation. Options: `:sync?` (default true) syncs after each user
operation."
situation. Options:
- `:sync?` (default true) syncs after each user operation;
- `:undo-check?` (default true, false when the case map turns the check
off) runs the undo/redo round trip of
`app.common.test-helpers.composable.comp.undo-check`; its failures are
recorded in the situation for `uc/check!`."
([case-map] (run-variant case-map {}))
([{:keys [setup operation]} opts]
(run-op (setup) operation (merge default-opts opts))))
([{:keys [setup operation] :as case-map} opts]
(let [opts (merge default-opts
{:undo-check? (uc/enabled? case-map)}
opts)]
(if (:undo-check? opts)
(-> (setup)
(uc/with-runner :pure)
(mark-baseline)
(run-op operation opts)
(check-variant))
(run-op (setup) operation opts)))))
(defn run-all
"Enumerate `operation` into its concrete variants and run each with
@ -218,4 +358,4 @@
resulting situations in enumeration order."
([case-map] (run-all case-map {}))
([case-map opts]
(tm/run-all case-map #(run-variant % opts))))
(tm/run-all case-map #(run-variant (merge case-map %) opts))))

View File

@ -5,23 +5,13 @@
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns app.common.test-helpers.composable.comp.setups
"Component-specific setups for the test model: named functions that build an
in-memory file value for a particular component configuration. They are the
subject-specific counterpart to the generic engine; a 'simple component with
a copy' is an entirely component-shaped configuration, so it lives behind the
`comp` boundary. See `mem:frontend/composable-component-tests`.
Setups are kept as plain functions (not data): structure resists
declarativization and forcing it here has the worst cost/benefit. Each returns
a *situation* (file + ROLE bindings — meaningful named objects of the
configuration, e.g. :main-instance, :copy-instance), which the test retrieves
via the accessors below and asserts on directly.
For these one-child-per-instance configurations the meaningful objects are the
child shapes that participate in propagation, so :main-instance is the main's
child and :copy-instance is the copy's child (this makes a test read like
`(has-attr? change-attr (copy-instance situation))`)."
"Setups of the composable component cases: functions that build a file
and return a situation with its roles (see
`mem:frontend/composable-component-tests`). In the one-child setups,
:main-instance and :copy-instance are the children of the main and the
copy."
(:require
[app.common.data :as d]
[app.common.files.changes-builder :as pcb]
[app.common.logic.shapes :as cls]
[app.common.test-helpers.components :as thc]
@ -31,6 +21,9 @@
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]))
;; The fill the labeled setups give the main child.
(def labeled-fill "#abcdef")
(defn simple-component-with-copy
"A situation with a simple component (root + one child) and one clean copy.
Shape labels: :main-root :main-child :copy-root :copy-child. Roles:
@ -46,28 +39,191 @@
:copy-root :copy-root})))
(defn empty-situation
"A situation with an empty file and NO roles — the starting point for scenarios
that build their own configuration via operations (e.g. `create-component`,
`make-nested-component`, `instantiate-copy`). Use as the `:setup` when the first
operation creates the component."
[]
(tm/make-situation (thf/sample-file :file1)))
(defn simple-component-with-labeled-copy
"Like `simple-component-with-copy`, but the main child starts with a known fill
(so 'value stayed' is distinguishable from coincidence). Same labels and roles."
(defn flex-component-with-copy
"Like `simple-component-with-copy`, with a 100x100 main root that has a
flex layout (row) and a 50x50 child. Same labels and roles."
[]
(let [file (-> (thf/sample-file :file1)
(tho/add-simple-component-with-copy
:component1 :main-root :main-child :copy-root
:main-child-params {:fills (ths/sample-fills-color :fill-color "#abcdef")}
:main-root-params {:layout :flex :layout-flex-dir :row
:width 100 :height 100}
:main-child-params {:width 50 :height 50}
:copy-root-params {:children-labels [:copy-child]}))]
(tm/make-situation file {:main-instance :main-child
:copy-instance :copy-child
:main-root :main-root
:copy-root :copy-root})))
(defn empty-situation
"A situation with an empty file and no roles, for cases that build their
configuration with operations (`create-component` and the like)."
[]
(tm/make-situation (thf/sample-file :file1)))
(defn simple-component-with-labeled-copy
"Like `simple-component-with-copy`, with the main child filled
`labeled-fill`. Same labels and roles."
[]
(let [file (-> (thf/sample-file :file1)
(tho/add-simple-component-with-copy
:component1 :main-root :main-child :copy-root
:main-child-params {:fills (ths/sample-fills-color :fill-color labeled-fill)}
:copy-root-params {:children-labels [:copy-child]}))]
(tm/make-situation file {:main-instance :main-child
:copy-instance :copy-child
:main-root :main-root
:copy-root :copy-root})))
(defn simple-component-with-copies-on-two-pages
"Like `simple-component-with-labeled-copy`, plus a second copy on another
page. The main and the first copy live on the current page `:page1`; the
second copy on `:page2`. Labels: :main-root :main-child :copy-root
:copy-child :copy2-root :copy2-child. Roles as in the labeled setup, plus
:other-page-copy-instance -> :copy2-child (read it with
`other-page-copy-instance`, since it is not on the current page)."
[]
(let [file (-> (thf/sample-file :file1 :page-label :page1)
(tho/add-simple-component-with-copy
:component1 :main-root :main-child :copy-root
:main-child-params {:fills (ths/sample-fills-color :fill-color labeled-fill)}
:copy-root-params {:children-labels [:copy-child]})
(thf/add-sample-page :page2)
(thc/instantiate-component :component1 :copy2-root
:children-labels [:copy2-child])
(thf/switch-to-page :page1))]
(tm/make-situation file {:main-instance :main-child
:copy-instance :copy-child
:main-root :main-root
:copy-root :copy-root
:other-page-copy-instance :copy2-child})))
(defn other-page-copy-instance
"The copy child on the other page (role :other-page-copy-instance), live."
[situation]
(tm/role-shape-in-file situation :other-page-copy-instance))
(defn simple-text-component-with-copy
"A component whose root (100x100) holds one text, \"hello world\", and a
clean copy. Labels: :main-root :main-text :copy-root :copy-text. Roles:
:main-instance -> the main text, :copy-instance -> the copy text, plus
:main-root and :copy-root."
[]
(let [file (-> (thf/sample-file :file1)
(tho/add-frame-with-text :main-root :main-text "hello world"
:frame-params {:width 100 :height 100}
;; the name a new text gets from its content
:child-params {:name "hello world"})
(thc/make-component :component1 :main-root)
(thc/instantiate-component :component1 :copy-root
:children-labels [:copy-text]))]
(tm/make-situation file {:main-instance :main-text
:copy-instance :copy-text
:main-root :main-root
:copy-root :copy-root})))
(defn- label-copy-children!
"Register each label of `labels` (main child label -> copy child label) on
the child of the copy `copy-label` that references that main child."
[file copy-label labels]
(let [objects (:objects (thf/current-page file))]
(doseq [[main-label copy-child-label] labels]
(thi/set-id! copy-child-label
(d/seek #(= (thi/id main-label) (get-in objects [% :shape-ref]))
(get-in objects [(thi/id copy-label) :shapes]))))))
(defn grid-component-with-copy
"A component whose main is a grid board (one row, three columns, 300x100)
holding two copies of an `:item` component in its first two columns, the
third free, and a copy of it. A second component, `:other`, has a red rect
(a swap target). Labels: :grid-root :child1 :child2 (main side),
:grid-copy :copy-child1 :copy-child2 (copy side), :item, :other. Roles:
:main-root, :copy-root, :main-child -> :child1, :copy-child -> :copy-child1."
[]
(let [file (-> (thf/sample-file :file1)
(tho/add-simple-component :item :item-root :item-rect
:root-params {:width 100 :height 100}
:child-params {:width 50 :height 50})
(tho/add-simple-component :other :other-root :other-rect
:root-params {:width 100 :height 100}
:child-params {:width 50 :height 50
:fills (ths/sample-fills-color
:fill-color "#ff0000")})
(tho/add-grid-frame :grid-root :width 300 :height 100)
(thc/instantiate-component :item :child1 :parent-label :grid-root)
(thc/instantiate-component :item :child2 :parent-label :grid-root)
(tho/place-in-grid-columns :grid-root 3 {1 :child1 2 :child2})
(thc/make-component :grid :grid-root)
(thc/instantiate-component :grid :grid-copy))]
(label-copy-children! file :grid-copy {:child1 :copy-child1 :child2 :copy-child2})
(tm/make-situation file {:main-root :grid-root
:copy-root :grid-copy
:main-child :child1
:copy-child :copy-child1})))
(defn grouped-component-with-copy
"A component whose main board holds a group with a copy of an `:item`
component, and a copy of it. A second component, `:other`, has a red rect
(a swap target). Labels: :grouped-root :group :child1 (main side),
:grouped-copy :copy-group :copy-child1 (copy side), :item, :other. Roles:
:main-root, :copy-root, :main-child -> :child1, :copy-child -> :copy-child1."
[]
(let [file (-> (thf/sample-file :file1)
(tho/add-simple-component :item :item-root :item-rect
:root-params {:width 100 :height 100}
:child-params {:width 50 :height 50})
(tho/add-simple-component :other :other-root :other-rect
:root-params {:width 100 :height 100}
:child-params {:width 50 :height 50
:fills (ths/sample-fills-color
:fill-color "#ff0000")})
(tho/add-frame :grouped-root :width 200 :height 200)
(tho/add-group :group :parent-label :grouped-root)
(thc/instantiate-component :item :child1 :parent-label :group)
(thc/make-component :grouped :grouped-root)
(thc/instantiate-component :grouped :grouped-copy))]
(label-copy-children! file :grouped-copy {:group :copy-group})
(label-copy-children! file :copy-group {:child1 :copy-child1})
(tm/make-situation file {:main-root :grouped-root
:copy-root :grouped-copy
:main-child :child1
:copy-child :copy-child1})))
(defn grid-component-with-copy-and-loose-item
"`grid-component-with-copy` plus a top-level copy of `:item`, labelled
:loose. Same roles, plus :loose."
[]
(let [situation (grid-component-with-copy)]
(-> situation
(tm/with-file (thc/instantiate-component (tm/file situation) :item :loose))
(assoc-in [:roles :loose] (thi/id :loose)))))
(defn component-with-sibling-instances
"A component whose main (300x100) holds three copies of an `:icon`
component side by side, and a copy of it. With `:grid` layout the main is a
one-row, three-column grid with each copy in its own cell. Labels: :row-root
:sub1 :sub2 :sub3 (main side), :row-copy :copy-sub1 :copy-sub2 :copy-sub3
(copy side, matched by :shape-ref). Roles: :main-root, :copy-root."
([] (component-with-sibling-instances :none))
([layout]
(let [grid? (= :grid layout)
subs [:sub1 :sub2 :sub3]
file (as-> (thf/sample-file :file1) $
(tho/add-simple-component $ :icon :icon-root :icon-rect
:root-params {:width 24 :height 24}
:child-params {:width 24 :height 24})
(if grid?
(tho/add-grid-frame $ :row-root :width 300 :height 100)
(tho/add-frame $ :row-root :width 300 :height 100))
(reduce #(thc/instantiate-component %1 :icon %2 :parent-label :row-root) $ subs)
(cond-> $
grid? (tho/place-in-grid-columns :row-root 3 (zipmap [1 2 3] subs)))
(thc/make-component $ :row :row-root)
(thc/instantiate-component $ :row :row-copy))]
(label-copy-children! file :row-copy (zipmap subs [:copy-sub1 :copy-sub2 :copy-sub3]))
(tm/make-situation file {:main-root :row-root
:copy-root :row-copy}))))
(defn main-instance
"The main child shape of the configuration (role :main-instance), live."
[situation]
@ -88,12 +244,22 @@
[situation]
(tm/role-shape situation :copy-root))
(defn misaligned-sub-heads
"The indices of the copy root's children whose :shape-ref is not the main
root's child at the same index (positional alignment)."
[situation]
(let [main (:shapes (main-root situation))
copy (:shapes (copy-root situation))
ref #(:shape-ref (tm/shape-by-id situation %))]
(->> (map vector (range) copy main)
(remove (fn [[_ c m]] (= m (ref c))))
(mapv first))))
(defn component-with-many-children
"A situation with a component whose main has three children and one clean copy.
Shape labels: :main-root, :main-child1/2/3, :copy-root, :copy-child1/2/3.
Roles: :main-root, :copy-root, and :copy-child-1/2/3 -> the copy's children
(so a test can assert their post-operation order in the copy root)."
"A component whose main has three children, and a copy. Labels: :main-root
:main-child1/2/3 :copy-root :copy-child1/2/3. Roles: :main-root,
:copy-root and :copy-child-1/2/3 -> the copy's children."
[]
(let [file (-> (thf/sample-file :file1)
(tho/add-component-with-many-children-and-copy
@ -109,30 +275,17 @@
:copy-child-3 :copy-child3})))
(defn copy-child
"The copy child shape for 1-based index `n` (role :copy-child-n), live. Lets a
test retrieve specific copy children to assert their order/identity."
"The copy child shape for 1-based index `n` (role :copy-child-n), live."
[situation n]
(tm/role-shape situation (keyword (str "copy-child-" n))))
(defn nested-component-with-copy
"A situation with a NESTED component configuration (depth axis): component2's
main contains a nested instance of component1 (`:main2-nested-head`); a clean
copy of component2 exists, so the copy contains a copy of that nested instance
whose child (`:copy2-child`) reaches the main through a :shape-ref CHAIN.
This is the depth-1 analogue of the simple-with-copy setup: editing
`:main2-nested-head` (the nested instance inside component2's main) and
propagating component2 must reach `:copy2-child` — the same attribute-
propagation property as the flat case, one level deeper. (Editing the
INNERMOST :main1-child and propagating only :component1 would instead be a
CHAINED propagation across two component levels — a different property; not
this setup.)
Shape labels from the helper: :main1-root/:main1-child, :main2-root,
:main2-nested-head, :copy2-root, and :copy2-child (the deep copy child, labeled
via the helper's children-labels). Roles: :main-instance -> :main2-nested-head,
:copy-instance -> :copy2-child, plus :main2-root / :copy-root for structure."
"Component2's main holds a copy of component1 (`:main2-nested-head`), and a
copy of component2 holds a copy of it. Labels: :main1-root :main1-child
:main2-root :main2-nested-head :copy2-root :copy2-child. Roles:
:main-instance -> :main2-nested-head, :copy-instance -> :copy2-child,
:main2-root and :copy-root."
[]
(let [file (-> (thf/sample-file :file1)
(tho/add-nested-component-with-copy
@ -147,10 +300,8 @@
(defn- change-main-child-fill
"Apply `fill-color` to the library's :main-child via the production change path
(mirrors how a real edit to the main would have changed the library), returning
the updated library file value. Used to make the library main DIVERGE from the
already-instantiated copy, so a subsequent cross-file sync has something to pull."
"`library` with its :main-child filled `fill-color`, through the production
change path."
[library fill-color]
(let [page (thf/current-page library)
main-id (thi/id :main-child)
@ -163,41 +314,73 @@
(thf/apply-changes library changes)))
(defn cross-file-component-with-copy
"LOCALITY axis (case H): a component whose main lives in a SEPARATE, shared
LIBRARY file, and a clean copy that lives in a CONSUMING file. The library main
has since DIVERGED from the copy (its :main-child now carries `new-fill`, while
the copy still carries the original `#abcdef`), modelling 'the library was
changed elsewhere'. Propagating that change to the copy is therefore a CROSS-
FILE sync (the library-update flow), not the in-file watcher.
The returned situation's PRIMARY file is the CONSUMING file (the current file,
where the copy lives and which the copy roles resolve against); the library
travels as an AUXILIARY file (see `tm/with-aux-files`) so an interpreter can
install it alongside (e.g. into the frontend store's `:files`) and run the
cross-file sync. Roles: :copy-instance -> the copy child, :copy-root -> the copy
root (both in the consuming file). `new-fill` should match the value the test
uses for its expected-value descriptor.
Labels: in the LIBRARY — :component1, :main-root, :main-child; in the CONSUMING
file — :copy-root, :copy-child."
"A component in a shared library file and a copy of it in the current
file; the library main then changes its child's fill to `new-fill`, so the
copy is behind it. The library travels as an auxiliary file. Labels: in
the library :component1 :main-root :main-child, in the file :copy-root
:copy-child. Roles: :copy-instance -> :copy-child, :copy-root."
[new-fill]
(let [library (-> (thf/sample-file :library :is-shared true)
(tho/add-simple-component
:component1 :main-root :main-child
:child-params {:fills (ths/sample-fills-color :fill-color "#abcdef")}))
;; instantiate the copy in the consuming file FIRST (copy gets the old fill)
:child-params {:fills (ths/sample-fills-color :fill-color labeled-fill)}))
file (-> (thf/sample-file :file)
(thc/instantiate-component :component1 :copy-root
:library library
:children-labels [:copy-child]))
;; THEN diverge the library main (copy is now stale)
library' (change-main-child-fill library new-fill)]
(-> (tm/make-situation file {:copy-instance :copy-child
:copy-root :copy-root})
(tm/with-aux-files {(:id library') library'}))))
(defn library-id
"The id of the library file in a cross-file situation (the single auxiliary
file). Used by the cross-file sync operation."
[situation]
(-> situation tm/aux-files keys first))
(defn cross-file-component-with-many-children
"A component with three children in a shared library file and a copy of it
in the current file; the library main then deletes its middle child, so
the copy is behind it. The library travels as an auxiliary file. Labels:
in the library :component1 :main-root :main-child1/2/3, in the file
:copy-root :copy-child1/2/3. Roles: :copy-root and :copy-child-1/2/3."
[]
(let [library (-> (thf/sample-file :library :is-shared true)
(tho/add-component-with-many-children
:component1 :main-root [:main-child1 :main-child2 :main-child3]))
file (-> (thf/sample-file :file)
(thc/instantiate-component :component1 :copy-root
:library library
:children-labels [:copy-child1
:copy-child2
:copy-child3]))
page (thf/current-page library)
[_ del] (cls/generate-delete-shapes (pcb/empty-changes nil (:id page))
(:data library)
page
(:objects page)
#{(thi/id :main-child2)}
{})
library' (thf/apply-changes library del)]
(-> (tm/make-situation file {:copy-root :copy-root
:copy-child-1 :copy-child1
:copy-child-2 :copy-child2
:copy-child-3 :copy-child3})
(tm/with-aux-files {(:id library') library'}))))
(defn component-nested-in-a-sub-board
"An `:inner` component (root and rect) and an `:outer` one whose main board
holds a sub-board with a copy of `:inner` in it, and a copy of `:outer`.
Labels: :inner-root :inner-rect, :outer-root :sub-board :nested,
:outer-copy. Roles: :main-instance -> :inner-rect, :main-root ->
:outer-root, :copy-root -> :outer-copy."
[]
(let [file (-> (thf/sample-file :file1)
(tho/add-simple-component :inner :inner-root :inner-rect
:root-params {:width 50 :height 50}
:child-params {:width 20 :height 20
:fills (ths/sample-fills-color
:fill-color labeled-fill)})
(tho/add-frame :outer-root :width 200 :height 200)
(tho/add-frame :sub-board :parent-label :outer-root :width 100 :height 100)
(thc/instantiate-component :inner :nested :parent-label :sub-board)
(thc/make-component :outer :outer-root)
(thc/instantiate-component :outer :outer-copy))]
(tm/make-situation file {:main-instance :inner-rect
:main-root :outer-root
:copy-root :outer-copy})))

View File

@ -0,0 +1,241 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns app.common.test-helpers.composable.comp.undo-check
"The undo/redo round trip that both composable runners run on every case
variant. With S(k) the normalized file after step k:
- after a user step k that adds an undo entry, undo must give back
S(k-1) and redo S(k); the variant then goes on from the redone file;
- a user step that adds no undo entry must change nothing;
- at the end of the variant, undoing back to the last assembly step must
give back the file after it, and redoing all again the final file.
Assembly steps do not go through the undo stack, so the check never undoes
past the last one. Inline `Test` operations are not run again.
The runners record each failed check in the situation, with its
`:signature`, the set of what differs (see `signature`), and `check!`
asserts on them after the case's own asserter. The case map's
`:undo-check` may hold:
- `:off`, the reason the case turns the check off;
- `:known-failures`, the failures a known bug causes: strict expected
failures that pin how the check fails. Each is a map of `:bug` (its
row in the plan's suspected bugs), `:fails` (phase -> the exact
signature the failure of that phase has), `:op` (the case's operation
node whose step fails, matched by node identity; any step when nil),
`:runners` (a subset of `#{:pure :frontend}`; both when nil) and
`:when` (a situation predicate).
A mark applies to a variant of its runners where its `:op` ran and
`:when` holds. A failure it does not pin exactly stays a failure, and
a pinned phase that does not fail fails the case, so the mark goes
only with the fix."
(:require
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.normalize :as thn]
[clojure.test :as t]
[clojure.walk :as walk]))
(defn with-runner
"Record in `situation` which runner runs it, `:pure` or `:frontend`, for
the `:runners` of known failures."
[situation runner]
(assoc situation ::runner runner))
(defn enabled?
"Whether `case-map` runs the round trip."
[case-map]
(not (contains? (:undo-check case-map) :off)))
(defn snapshot
"The normalized value of `file` that the round trip compares."
([file] (snapshot file {}))
([file opts] (thn/normalize-file file opts)))
(defn mark-baseline
"Record the state the end-of-variant round trip undoes back to: the
normalized file `snap` with `depth` undo groups on the stack."
[situation depth snap]
(assoc situation ::baseline {:depth depth :snapshot snap}))
(defn baseline
"The state recorded by `mark-baseline`, as `{:depth :snapshot}`."
[situation]
(::baseline situation))
(defn step
"The step of operation `op` in `situation`, as failures name it: the node
`:id` and its `:description` in the transcript."
[situation op]
{:id (tm/node-id op)
:description (tm/describe-application situation op)})
(defn- add-failure
[situation failure]
(update situation ::failures (fnil conj []) failure))
(defn add-error
"Record that the round trip could not run `phase` at `step` (see `step`;
nil for the end-of-variant phases): `error` says why."
[situation step phase error]
(add-failure situation {:phase phase
:step step
:signature #{[:error]}
:error error}))
(defn- labelled
"`value` with every uuid replaced by its test label. Labels are valid only
while the variant that registered them runs."
[value]
(walk/postwalk #(if (uuid? %) (thi/label %) %) value))
(defn- label-of
"The test label of `id`, or `:unlabelled`, so a signature is the same in
every run."
[id]
(let [label (thi/label id)]
(if (keyword? label) label :unlabelled)))
(defn- differing-keys
"The keys, other than those in `skip`, whose values differ between the maps
`expected` and `actual`."
[expected actual skip]
(->> (into (set (keys expected)) (keys actual))
(remove skip)
(filter #(not= (get expected %) (get actual %)))))
(defn- entities-signature
"What differs between the maps of entities by id `expected` and `actual`:
`[kind label attr]` for an attribute, `[kind label :missing]` or
`[kind label :extra]` for an entity on one side only. `inner` gives the
entries of what differs inside an entity present on both sides, for the
attributes it skips."
[kind expected actual skip inner]
(into #{}
(mapcat (fn [id]
(let [e (get expected id)
a (get actual id)
label (label-of id)]
(cond
(= e a) nil
(nil? a) [[kind label :missing]]
(nil? e) [[kind label :extra]]
:else (concat (for [attr (differing-keys e a skip)]
[kind label attr])
(inner e a))))))
(into (set (keys expected)) (keys actual))))
(defn signature
"What differs between the normalized files `expected` and `actual`, as a
set of entries: `[:object label attr]` for a shape attribute (or `:missing`
/ `:extra` for a whole shape), the same with `:page` and `:component`, and
`[:data key]` / `[:file key]` for anything else. Shapes without a test
label are `:unlabelled`."
[expected actual]
(let [ed (:data expected)
ad (:data actual)]
(-> #{}
(into (map #(vector :file %)) (differing-keys expected actual #{:data}))
(into (map #(vector :data %)) (differing-keys ed ad #{:pages-index :components}))
(into (entities-signature :page (:pages-index ed) (:pages-index ad) #{:objects}
(fn [e a]
(entities-signature :object (:objects e) (:objects a)
#{} (constantly nil)))))
(into (entities-signature :component (:components ed) (:components ad)
#{} (constantly nil))))))
(defn compare-states
"Record a failure of `phase` at `step` unless the normalized files
`expected` and `actual` are equal. Phases: `:undo`, `:redo`,
`:no-undo-entry` (a step that added no entry changed the file),
`:variant-undo` and `:variant-redo`."
[situation step phase expected actual]
(if (= expected actual)
situation
(add-failure situation {:phase phase
:step step
:signature (signature expected actual)
:diff (labelled (thn/diff expected actual))})))
(defn compare-index
"Record a failure of `phase` at `step` unless the workspace undo index is
`expected`: its signature is `#{[:undo-index n]}`, with `n` the entries
the index is off by. Phases: `:undo-index` and `:redo-index`."
[situation step phase expected actual]
(if (= expected actual)
situation
(add-failure situation {:phase phase
:step step
:signature #{[:undo-index (- actual expected)]}
:error (str "undo index " actual ", expected " expected)})))
(defn failures
"The failed checks recorded in `situation`, in order."
[situation]
(get situation ::failures []))
(defn- matches?
"Whether the known failure `mark` pins `failure` exactly."
[{:keys [fails op]} failure]
(and (= (get fails (:phase failure)) (:signature failure))
(or (nil? op)
(nil? (:step failure))
(= (tm/node-id op) (get-in failure [:step :id])))))
(defn- check-mark!
[{:keys [bug fails] :as mark}]
(when-not (and (map? fails) (seq fails))
(throw (ex-info (str "Known undo failure " bug " pins no failure: give it "
"`:fails`, phase -> signature")
{:type ::unpinned-mark
:mark mark}))))
(defn verdict
"The failures of `situation`, a variant of `case-map`, that no known failure
of the case pins (`:unexpected`), and the pinned phases of the known
failures that apply to the variant but did not fail as pinned
(`:resolved`, each the mark with its `:phase`)."
[situation case-map]
(let [marks (get-in case-map [:undo-check :known-failures])
_ (run! check-mark! marks)
applies? (fn [{:keys [op runners] pred :when}]
(and (or (nil? runners) (contains? runners (::runner situation)))
(or (nil? op) (tm/applied? situation op))
(or (nil? pred) (pred situation))))
known (filter applies? marks)
found (failures situation)]
{:unexpected (filterv (fn [failure] (not-any? #(matches? % failure) known)) found)
:resolved (vec (for [mark known
phase (keys (:fails mark))
:when (not-any? #(and (= phase (:phase %)) (matches? mark %))
found)]
(assoc mark :phase phase)))}))
(defn- describe-failure
[{:keys [phase step signature diff error]}]
(str "Undo check failed: " (name phase)
(when step (str " of step " (:description step)))
"\n signature: " (pr-str signature)
(if error
(str "\n error: " error)
(str "\n expected only: " (pr-str (first diff))
"\n actual only: " (pr-str (second diff))))))
(defn check!
"Assert that the round trip of `situation`, a variant of `case-map`, found
no failure but the case's known ones, and that each known one happened."
[situation case-map]
(when (enabled? case-map)
(let [{:keys [unexpected resolved]} (verdict situation case-map)]
(doseq [failure unexpected]
(t/is false (describe-failure failure)))
(doseq [{:keys [bug phase fails op]} resolved]
(t/is false (str "Known undo failure " bug " did not fail as pinned: "
(name phase) " " (pr-str (get fails phase))
(when op (str " of step " (pr-str (dissoc (into {} op) ::tm/id))))
". If the fix landed, remove the mark in the fix commit; "
"otherwise the failure changed: see the failures above"))))))

View File

@ -5,70 +5,39 @@
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns app.common.test-helpers.composable.core
"The domain-agnostic ENGINE of the composable test model (see
`mem:frontend/composable-component-tests`):
"The domain-agnostic engine of the composable test model (see
`mem:frontend/composable-component-tests`): the situation (file, roles,
vars and the log of applied operations), node identity, strict-presence
lookup, the `IOperation` and `IEnumerable` protocols, the operators
`in-sequence`, `one-of`, `optional`, `skip` and `test-that`, and the plain
runners `run-variant` / `run-all`. Component operations live behind the
`comp` boundary (`app.common.test-helpers.composable.comp.*`).
- a `situation` carrying the in-memory file value, named ROLE bindings,
a `:vars` map, and an ordered record of applied operations,
- node identity (`assign-id`) + the applied-log (`record-application`,
`applied?`, `describe-applied`),
- strict-presence lookup that throws a diagnostic error on a missing name,
- the `IOperation` protocol (single method `apply-to`) and the
`IEnumerable` protocol behind variant enumeration,
- the composition operators `in-sequence`, `one-of`, `optional`, `skip`,
and the inline-assertion operation `test-that`,
- the enumerating pure runners `run-variant` / `run-all` (the frontend
interpreter in `frontend-tests.composable-tests.interpreter` is the
event-dispatching counterpart and the test-facing entry point).
No Penpot domain terms live here; the component-specific operations sit
behind the `comp` boundary (`app.common.test-helpers.composable.comp.*`).
Shape references use the existing label->uuid system (`app.common.test-helpers.ids-map`)
rather than a parallel binding map: a binding name in an operation IS a
shape label, resolved through `thi/id`. The situation adds the applied-log and
the strict-presence discipline on top of that substrate."
A shape name in an operation is a test label (`app.common.test-helpers.ids-map`)."
(:refer-clojure :exclude [apply-to])
(:require
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.types.pages-list :as ctpl]
[app.common.types.shape-tree :as ctst]
[app.common.uuid :as uuid]
[clojure.string :as str]))
[clojure.string :as str]
[clojure.test :as t]))
;; ---------------------------------------------------------------------------
;; Situation
;;
;; A situation wraps the in-memory Penpot file value together with the record of
;; what has been applied to it. The environment of *shape* bindings is the
;; global label->uuid map (reset per variant by the runners), so the situation
;; does not duplicate it; it only adds:
;; :file - the current in-memory file value
;; :applied-log - vector of application records, in application order
;; Situation: the in-memory file value with its roles, vars and the log of
;; what was applied to it. Shape labels live in the global label map, which
;; the runners reset per variant.
;; ---------------------------------------------------------------------------
;; resolve-shape is defined below (strict-presence section) but referenced by
;; role-shape above it; declare it so the forward reference resolves at load.
(declare resolve-shape)
(declare resolve-shape-id)
(defn make-situation
"Create a situation from an initial in-memory file value, optionally with role
bindings. Roles are meaningful named objects of the configuration the setup
built (e.g. :main-instance, :copy-instance), passed as shape *labels*. The
labels are resolved to ids IMMEDIATELY (at construction, while the labels are
freshly valid) and the situation stores the resolved ids. This is essential:
the global label->id map is time-varying and shared, so resolving a role label
later (e.g. in another enumerated variant's run) would be unsound; capturing
the id at setup time makes each situation resolve its roles against the file it
was built with, independent of the global map's later state.
The situation also carries:
:applied - ordered vector of operation ids, in application order
(so the full sequence is always recoverable from the situation)
:node-data - map of operation-id -> the record that operation
wrote about its own application (keyed by NODE IDENTITY, not by
a node-kind tag), so each node retrieves its own record."
"A situation for `file`, with `roles` (role key -> shape label) resolved to
ids at once: the label map changes from variant to variant, so a role keeps
the id of the file it was built with. `:applied` holds the ids of the
applied operations in order, `:node-data` what each recorded about its
application."
([file] (make-situation file {}))
([file roles]
{:file file
@ -83,20 +52,15 @@
(:file situation))
(defn with-file
"Return a situation with its file value replaced (the threaded result of
applying a transformation through the production change pipeline)."
"`situation` with its file replaced by `file'`."
[situation file']
(assoc situation :file file'))
(defn with-aux-files
"Return a situation carrying AUXILIARY files (a map of file-id -> file value)
beyond the primary `:file`. Used by cross-file configurations (e.g. a copy in
the primary/current file whose main lives in a linked LIBRARY file): the
primary `:file` stays the current file the role accessors resolve against,
while the auxiliary files travel alongside so an interpreter can install them
too (e.g. into the frontend store's `:files`, so cross-file sync can run).
The primary file is NOT included here."
"`situation` with auxiliary files (file id -> file), such as a linked
library, besides its current file. Roles resolve against the current file;
an interpreter installs the auxiliary ones next to it."
[situation files-by-id]
(assoc situation :aux-files files-by-id))
@ -106,14 +70,10 @@
[situation]
(get situation :aux-files {}))
;; ----- Node identity (central, no inheritance) -----------------------------
;; ----- Node identity -------------------------------------------------------
;;
;; Records are value-equal in Clojure, so two structurally-identical nodes would
;; collide as map keys. Each node therefore carries an explicit unique id under
;; the reserved key ::id, stamped at construction by `assign-id` (the single
;; thing every node constructor must call). The id machinery — stamping, and the
;; record/retrieve-by-id pair below — is implemented ONCE here and shared by all
;; nodes as plain functions; nodes never reimplement it, they just pass `this`.
;; Records with equal fields are equal, so every node constructor stamps a
;; unique id under ::id with `assign-id`; what a node records is keyed by it.
(defn assign-id
"Stamp a fresh unique id onto a node record (reserved key ::id). Every node
@ -129,9 +89,8 @@
;; ----- Self-description, keyed by node identity ----------------------------
(defn- node-kind
"A short readable kind name for a node, derived from its record type (no
per-node boilerplate, faithful to the actual type). E.g. a ChangeAttr record
yields \"change-attr\"."
"The kebab-case name of a node's record type: a ChangeProperty record
yields \"change-property\"."
[node]
(let [cls (or #?(:clj (some-> ^Class (type node) .getSimpleName)
:cljs (some-> node type .-name (str/split #"\.") last))
@ -143,66 +102,53 @@
kebab))
(defn record-application
"Record what an operation `node` did into `situation`, keyed by the node's
identity, and append its id to the ordered :applied sequence. `record` is an
arbitrary map describing the application; the node retrieves it later via
`node-data` by passing itself. The node's kind (from its type) is merged in
under ::kind so the application can be rendered (see `describe-applied`)
without the node needing to name itself. Both consumers (inspection methods,
undo) read through node identity and ignore the extra ::kind key."
"Record in `situation` that `node` was applied, with `record`, a map of what
it did, under its identity (read back with `node-data`). The node's kind
goes in under ::kind for `describe-applied`."
[situation node record]
(-> situation
(update :applied conj (node-id node))
(assoc-in [:node-data (node-id node)] (assoc record ::kind (node-kind node)))))
(defn node-data
"The record that `node` wrote about its own application in `situation`, or nil
if it has not been applied. Keyed by node identity."
"What `node` recorded about its application in `situation`, or nil when it
was not applied."
[situation node]
(get-in situation [:node-data (node-id node)]))
(defn applied-ids
"The ordered vector of operation ids applied to the situation (the full
sequence, recoverable from the situation)."
[situation]
(:applied situation))
(defn applied?
"Whether `operation` ran in this situation. Identity-based: true iff this exact
operation node (by its `::id`) recorded an application. Works through `optional`
/ `one-of`: a chosen alternative records itself under its own identity, so
querying with the raw operation answers correctly. Bind an operation to a value
ONCE and reuse it (in the composition AND in any `Test` that queries it), so the
id you ask about is the id that ran."
"Whether this exact `operation` node ran in `situation`, also when it was
the chosen alternative of a `one-of` or `optional`. Bind an operation to a
value once and use that value both in the composition and in the query."
[situation operation]
(contains? (:node-data situation) (node-id operation)))
(defn- render-application
"Render one (non-choice) application record as a short human-readable string.
Content-agnostic: uses ::kind and the record's own fields."
"One application record (not a choice) as a short readable line."
[record]
(let [kind (::kind record)
args (dissoc record ::kind)]
(str kind (when (seq args) (str " " (pr-str args))))))
(defn describe-application
"A one-line description of what `node` recorded about its application in
`situation` (see `describe-applied`), or nil if it has not been applied."
[situation node]
(some-> (node-data situation node) render-application))
(defn describe-applied
"A human-readable, ordered transcript of the operations that produced
`situation` — one line per application, in order. Built purely from the
situation's recorded :applied ids and :node-data records (each node's own
self-description), so it is faithful to what actually ran, including the branch
a one-of chose. Used to label failures with the exact sequence at hand."
"The transcript of the operations that produced `situation`, one line per
application in order, including the branch each one-of chose. Failures
are labelled with it."
[situation]
(let [node-data (:node-data situation)]
(->> (:applied situation)
(keep (fn [id]
(let [record (get node-data id)]
(if (contains? record :chosen)
;; a one-of's choice record: if the chosen node recorded its
;; own application, its own line (also in :applied) already
;; tells the story — emit nothing to avoid a duplicate line.
;; Only a non-recording choice (a skipped `optional`) is
;; rendered here, so a skip stays visible in the transcript.
;; a choice gets a line only when the chosen node has none
;; of its own, such as a skipped `optional`
(let [chosen (:chosen record)]
(when-not (contains? node-data (::id chosen))
(str "one-of -> " (render-application {::kind (node-kind chosen)}))))
@ -210,18 +156,10 @@
(str/join "\n "))))
;; ----- Role accessors ------------------------------------------------------
;;
;; A setup records role bindings (meaningful named objects of the configuration)
;; as shape labels. `role-shape` resolves a role to the live shape in the current
;; file, with strict presence: an absent role throws diagnostically (never nil).
;; Specific named accessors (e.g. copy-instance) are thin wrappers, so tests read
;; `(copy-instance situation)` rather than knowing the role key.
(defn role-shape
"Resolve role `role-key` to the live shape in the situation's current file,
using the id captured at setup time. Throws a diagnostic error if the role is
not bound, or if its captured shape is no longer present in the current page
(e.g. it was deleted) — never returns nil silently."
"The live shape of role `role-key` in the situation's current page. Throws
when the role is not bound or its shape is not in the page."
[situation role-key]
(let [id (get-in situation [:roles role-key])
page (thf/current-page (file situation))]
@ -246,59 +184,51 @@
(contains? (:roles situation) role-key))
(defn shape-by-id
"The live shape with `id` in the situation's current page (nil if absent). For
reading a shape whose id is held outside the role map — e.g. a field of a
tracked component object."
"The live shape with `id` in the situation's current page, or nil."
[situation id]
(ctst/get-shape (thf/current-page (file situation)) id))
(defn rebind-role
"Re-point `role-key` to the current id of shape `label` (resolved via the global
label map now, while it is valid). Used by state-building operations that move
the configuration (e.g. `make-nested-component`) and must update where a role points so
that role-targeted operations keep acting on the intended shape."
[situation role-key label]
(assoc-in situation [:roles role-key] (thi/id label)))
(defn find-shape
"The live shape with `id` in any page of the situation's file (nil if
absent). For shapes outside the current page."
[situation id]
(some #(ctst/get-shape % id) (ctpl/pages-seq (:data (file situation)))))
(defn rebind-role-id
"Like `rebind-role`, but re-points `role-key` to a shape `id` directly (when the
operation discovered the shape by id, e.g. by following a :shape-ref chain,
rather than by label)."
[situation role-key id]
(assoc-in situation [:roles role-key] id))
(defn role-shape-in-file
"Like `role-shape`, but finds the role's shape in any page of the file."
[situation role-key]
(let [id (get-in situation [:roles role-key])]
(when (nil? id)
(throw (ex-info (str "Unbound role: " (pr-str role-key))
{:type ::unbound-role
:role role-key})))
(or (find-shape situation id)
(throw (ex-info (str "Role " (pr-str role-key) " resolves to a shape no longer "
"present in the file (id " (pr-str id) ").")
{:type ::role-shape-absent
:role role-key
:id id})))))
;; ---------------------------------------------------------------------------
;; Situation vars — arbitrary named values beyond roles
;;
;; Roles name SHAPES (resolved from labels to ids). Some operations need to track
;; named values that are NOT shapes — e.g. a component id to instantiate next, or
;; a counter (nesting depth). Those live in a separate `:vars` map so they do not
;; get confused with shape roles. Set/read with `set-var`/`get-var`.
;; Situation vars: named values that are not shapes, such as a component id
;; or a nesting count.
;; ---------------------------------------------------------------------------
(defn set-var
"Associate `k` with `v` in the situation's `:vars` (arbitrary named values that
are NOT shapes — e.g. a component id, a counter). Returns the situation."
"`situation` with var `k` set to `v`."
[situation k v]
(assoc-in situation [:vars k] v))
(defn get-var
"Read the value of `k` from the situation's `:vars`, or `default` (nil if
omitted) when absent. See `set-var`."
"The value of var `k` in `situation`, or `default`."
([situation k] (get-var situation k nil))
([situation k default] (get-in situation [:vars k] default)))
(defn target-shape-id
"Resolve an operation's target to a shape id:
- a FUNCTION `(situation -> id)` is called with the situation (lets the target
be computed from situation state — e.g. a field of a tracked object —
resolved at apply-time so it follows state changes);
- a currently-bound ROLE resolves via the role (so the operation follows the
role as state-building ops re-point it);
- otherwise `target` is a label (strict-presence).
This is what makes a single operation composable across depth / with
make-nested-component et al."
"The shape id an operation's `target` names, resolved when the operation
applies: a `(situation -> id)` fn is called, a bound role gives its shape,
anything else is a label (strict presence)."
[situation target]
(cond
(fn? target) (target situation)
@ -306,20 +236,13 @@
:else (resolve-shape-id situation target)))
;; ---------------------------------------------------------------------------
;; Strict-presence lookup
;;
;; Resolving a binding name (shape label) that is absent must throw a DIAGNOSTIC
;; error: it names the absent binding and lists those present. A silently-nil
;; lookup is forbidden (it would make a declarative case a lie / a green test
;; that asserts against nothing). Acting on a present-but-wrong-kind binding is
;; left to crash naturally downstream.
;; Strict-presence lookup: an absent label throws, naming the labels present,
;; so a case never asserts against nil.
;; ---------------------------------------------------------------------------
(defn resolve-shape
"Resolve a shape binding name (label) to the actual shape in the situation's
current page, throwing a diagnostic error if the name is not bound to a shape
that exists in that page. The diagnostic lists the labels of the shapes that
ARE present, derived from the file itself (not from a parallel binding map)."
"The shape labelled `name` in the situation's current page. Throws, listing
the labels present, when there is none."
[situation name]
(let [the-file (file situation)
page (thf/current-page the-file)
@ -338,72 +261,41 @@
shape))
(defn resolve-shape-id
"Resolve a shape binding name (label) to its uuid, with strict-presence
diagnostics (see `resolve-shape`)."
"The id of the shape labelled `name` (see `resolve-shape`)."
[situation name]
(:id (resolve-shape situation name)))
;; ---------------------------------------------------------------------------
;; Operation protocol
;;
;; An OPERATION is a step in a composition. Most operations TRANSFORM the
;; situation (an edit, a structural change, a nesting), but some do not (a `Test`
;; asserts and returns the situation unchanged; `Skip` is a no-op) — hence the
;; genus is "operation", not "transformation". An operation is reified as DATA (a
;; record), not a bare function, so it is printable and navigable. `apply-to`
;; takes the operation and a situation and returns a (possibly identical)
;; situation; it may also record its own application. The method cannot be named
;; `apply` (core clash).
;; Operation protocol: a step of a composition, as a record so it prints.
;; `apply-to` returns the situation after it, recording its application.
;; ---------------------------------------------------------------------------
(defprotocol IOperation
(apply-to [operation situation]
"Apply this operation to `situation`, returning a (possibly identical)
situation."))
"`situation` after this operation."))
;; ---------------------------------------------------------------------------
;; Enumeration
;;
;; A composed operation may stand for MANY concrete cases (because `one-of`
;; offers alternatives). Enumeration turns one composed operation into the
;; sequence of fully-concrete operations it represents — each of which has
;; no remaining choice and can be `apply-to`'d directly.
;;
;; Enumeration is a generic-engine concern: only the composition operators
;; (`in-sequence`, `one-of`) implement it. Leaf/subject operations (e.g. the
;; component nodes) need not know about it — the top-level `enumerate` falls back
;; to "an operation with no choice enumerates to itself", so a plain node yields a
;; single variant (itself). This keeps `apply-to` and `enumerate` orthogonal and
;; keeps the `comp` node library free of enumeration code.
;; Enumeration: a composed operation stands for one concrete operation per
;; combination of its choices. Only the operators implement `IEnumerable`; any
;; other operation enumerates to itself.
;; ---------------------------------------------------------------------------
(defprotocol IEnumerable
(-enumerate [operation]
"Return a sequence of fully-concrete operations this one represents."))
"The concrete operations, with no choice left, this one stands for."))
(defn enumerate
"The concrete operations represented by `operation`. Falls back to a single
variant (the operation itself) for anything that does not implement
IEnumerable (i.e. leaf operations with no internal choice)."
"The concrete operations `operation` stands for."
[operation]
(if (satisfies? IEnumerable operation)
(-enumerate operation)
[operation]))
;; ---------------------------------------------------------------------------
;; Composition operator: sequence
;;
;; A `Sequence` holds an ordered vector of child operations and applies them
;; left-to-right, THREADING the situation through each: the situation returned
;; by one child is the input to the next. Operations do not commute, so order
;; is explicit. Its enumeration is the CARTESIAN PRODUCT of its children's
;; variants (with single-variant children this is exactly one Sequence), which
;; is what makes a `one-of`/`optional` composed inside a sequence multiply the
;; case out into a matrix.
;;
;; The constructor is named `in-sequence` because `sequence` is a clojure.core
;; name and must not be shadowed.
;; Sequence: applies its steps in order, threading the situation. It
;; enumerates to the cartesian product of its steps' variants, which is what
;; multiplies a case out into a matrix. (`sequence` is a core name, hence
;; `in-sequence`.)
;; ---------------------------------------------------------------------------
(declare ->Sequence)
@ -417,45 +309,30 @@
IEnumerable
(-enumerate [_]
;; Cartesian product: every combination of one concrete variant per step,
;; each combination rewrapped as a concrete Sequence. With single-variant
;; steps this yields exactly one Sequence (the all-singletons case).
(->> steps
(map enumerate) ; step -> seq of concrete variants
(map enumerate)
(reduce (fn [acc step-variants]
(for [combo acc
variant step-variants]
(conj combo variant)))
[[]]) ; seed: one empty combination
[[]])
(map ->Sequence))))
(defn in-sequence
"Constructor for the sequence operator: apply `steps` (a seq of
transformations) in order, threading the situation through each."
"Constructor for the sequence operator: apply `steps` in order."
[steps]
(->Sequence (vec steps)))
;; ---------------------------------------------------------------------------
;; Composition operator: one-of
;;
;; `one-of` offers a set of alternative transformations: it represents N cases,
;; one per alternative. It is a pure *enumeration* construct — it has no single
;; apply semantics, because applying it would mean arbitrarily picking one
;; alternative. So `apply-to` on a raw OneOf is an error; it must be enumerated
;; first (the runner does this). Its `-enumerate` is the UNION of its
;; alternatives' enumerations, so `one-of` composed inside `in-sequence`
;; multiplies out correctly via the sequence's cartesian product.
;; One-of: one case per alternative. It cannot be applied, only enumerated:
;; each variant is a `RecordedChoice` that records which alternative ran.
;; ---------------------------------------------------------------------------
(declare record-choice)
(defrecord RecordedChoice [one-of-id chosen]
;; Internal node produced by OneOf enumeration. Applying it records, under the
;; originating one-of's identity, which alternative was chosen, then applies
;; that alternative. This is how `get-choice` (read by the test holding the
;; one-of) recovers the choice from the resulting situation. It is already
;; concrete, so it enumerates to itself.
;; A variant of a one-of: records the choice under the one-of's identity
;; (see `get-choice`), then applies the chosen operation.
IOperation
(apply-to [this situation]
(->> (record-choice situation this)
@ -474,22 +351,16 @@
IEnumerable
(-enumerate [this]
;; Each alternative may itself enumerate to several concrete variants; every
;; resulting concrete variant is wrapped so that, when applied, it records
;; this one-of's choice under this one-of's identity.
(for [alt alternatives
variant (enumerate alt)]
(->RecordedChoice (node-id this) variant))))
(defn one-of
"Constructor for the one-of operator: represents one case per alternative in
`alternatives`. Used to sweep a set of variants (e.g. several attribute
changes) across an otherwise-shared case. Carries an identity so the choice it
made in a given enumerated run can be recovered via `get-choice`."
"Constructor for the one-of operator: one case per alternative of
`alternatives`. Ask it which one ran with `get-choice`."
[alternatives]
(assign-id (->OneOf (vec alternatives))))
(defrecord Skip []
IOperation
(apply-to [_ situation] situation)
@ -497,18 +368,12 @@
(-enumerate [self] [self]))
(defn skip
"The identity operation: applies as a no-op, enumerates to itself. The building
block of `optional`."
"The operation that changes nothing."
[]
(->Skip))
(defrecord Test [assert-fn]
;; An operation that makes ASSERTIONS at this point in the sequence and leaves
;; the situation unchanged. `assert-fn` is a (situation -> any) that performs the
;; assertions itself (e.g. calls `t/is`), exactly like an external asserter — so
;; checks can be placed at INTERMEDIATE steps, not only at the end. It records
;; its application (so the transcript shows where checkpoints sit) but changes
;; nothing. Concrete, so it enumerates to itself.
;; Runs assertions at its point of the sequence and changes nothing.
IOperation
(apply-to [this situation]
(assert-fn situation)
@ -517,60 +382,37 @@
(-enumerate [self] [self]))
(defn test-that
"Constructor for an inline `Test` operation. `assert-fn` is a (situation -> any)
that performs assertions (it is run for side effects; its return is ignored).
Place it inside an `in-sequence` to assert at that point in the trajectory.
Typically queries `applied?`/`get-choice`/`has-property-of` to decide what to
assert for the current enumerated variant."
"Constructor for an inline assertion: `assert-fn` (situation -> any) runs
its assertions at this point of the sequence."
[assert-fn]
(assign-id (->Test assert-fn)))
(defn optional
"`(optional t)` = `(one-of [t (skip)])`: sweeps WITH and WITHOUT `t` across a
case (two enumerated variants). Kept as its own named constructor for
readability. The workhorse for adding a state-building step (e.g.
`(optional (make-nested-component))`) as an axis over an existing case."
"`(one-of [t (skip)])`: the case with and without `t`."
[t]
(one-of [t (skip)]))
(defn get-choice
"The alternative this `one-of` chose in `situation` (the concrete transformation
that actually ran for this branch), or nil if it did not run in this variant.
Recovered by node identity, so the test holds the one-of and asks it."
"The alternative `one-of` chose in `situation`, or nil when it did not run."
[situation one-of]
(:chosen (node-data situation one-of)))
;; ---------------------------------------------------------------------------
;; Executors
;;
;; Build a fresh situation from a setup thunk and apply a (possibly composed)
;; OPERATION. `run-variant` runs one already-concrete variant; `run-all`
;; enumerates a composed operation and runs every variant. Neither makes a
;; judgment or touches clojure.test — `check` (in
;; `frontend-tests.composable-tests.interpreter`) is the test-facing entry point. (Assertions can also live INSIDE the operation, via
;; `Test`; those fire as the operation is applied.)
;; Plain runners: apply operations only, with no sync, undo or judgment. The
;; component cases run through `comp.runner` or the frontend interpreter.
;; ---------------------------------------------------------------------------
(defn run-variant
"Run one concrete (already-enumerated) variant: build a fresh situation via
`setup` (a 0-arg fn returning a *situation*) and apply `operation`,
returning the resulting situation. Makes no judgment. Exceptions propagate.
This is the per-variant step `check` builds on; tests use `check`, not this."
"The situation after applying the concrete `operation` to a fresh one from
`setup`."
[{:keys [setup operation]}]
(->> (setup)
(apply-to operation)))
(defn run-all
"Enumerate `operation` into its concrete variants and run each (fresh setup
per variant, isolated label space — the id map is reset before each variant's
setup so per-variant setups don't clobber labels). Returns a vector of the
resulting situations, one per enumerated variant, in enumeration order. Makes
no judgment and does not touch clojure.test — see `check` (in
`frontend-tests.composable-tests.interpreter`) for the test-facing entry point that asserts.
`run-variant-fn` runs one variant from `{:setup :operation}` (default
`run-variant`); other runners pass their own."
"The resulting situations of every variant of `operation`, in order, each
run by `run-variant-fn` (default `run-variant`) on `{:setup :operation}`
with a fresh label map."
([case-map] (run-all case-map run-variant))
([{:keys [setup operation]} run-variant-fn]
(->> (enumerate operation)
@ -579,18 +421,10 @@
(run-variant-fn {:setup setup
:operation variant}))))))
(defn sequence-ops
"Flatten a CONCRETE (already-enumerated) operation into its ordered units.
Used by alternative interpreters (e.g. the frontend one) that dispatch
per-operation effects rather than calling `apply-to`.
A concrete variant is a single operation record, or a `Sequence` of them, with
`RecordedChoice` (the enumerated form of a one-of) appearing where a one-of was.
`Sequence` is flattened; a `RecordedChoice` is KEPT as a unit (it carries both
the chosen operation and the one-of identity, so a per-op interpreter can
dispatch the chosen op's effect AND record the choice for `get-choice`). Use
`recorded-choice?`, `choice-of`, and `choice-one-of-id` to handle those units."
"The steps of the concrete `variant`, in order, with sequences flattened. A
`RecordedChoice` stays one step, so an interpreter can record the choice
(`record-choice`) and run the chosen operation (`choice-of`)."
[variant]
(cond
(instance? Sequence variant)
@ -600,12 +434,12 @@
[variant]))
(defn sequence?
"True if `op` is a `Sequence`; its ordered steps are under `:steps`."
"Whether `op` is a `Sequence`; its steps are under `:steps`."
[op]
(instance? Sequence op))
(defn recorded-choice?
"True if `op` is a one-of's enumerated choice wrapper."
"Whether `op` is a `RecordedChoice`, a variant of a one-of."
[op]
(instance? RecordedChoice op))
@ -615,17 +449,32 @@
(:chosen recorded-choice))
(defn choice-one-of-id
"The identity of the one-of that produced this `RecordedChoice` (so a per-op
interpreter can record the choice under it, enabling `get-choice`)."
"The identity of the one-of a `RecordedChoice` comes from."
[recorded-choice]
(:one-of-id recorded-choice))
(defn record-choice
"Record in `situation` the alternative `recorded-choice` selected, under its
one-of's identity, so `get-choice` finds it. Runners call it before applying
the chosen operation."
one-of's identity, for `get-choice`."
[situation recorded-choice]
(-> situation
(assoc-in [:node-data (choice-one-of-id recorded-choice)]
{:chosen (choice-of recorded-choice)})
(update :applied conj (choice-one-of-id recorded-choice))))
;; ---------------------------------------------------------------------------
;; Known failures: an assertion a known bug breaks pins the wrong value the
;; bug gives, so the case fails when the failure changes or stops.
;; ---------------------------------------------------------------------------
(defn known-failure
"Assert a strict expected failure for `bug` (its row in the plan's suspected
bugs): `expected` is the value that should hold and `actual` the value
found. While the bug is open, `actual` must be exactly `pinned`, the wrong
value the bug gives; any other value fails, `expected` included."
[bug expected pinned actual]
(t/is (= pinned actual)
(str "Known failure " bug ": expected " (pr-str expected)
", pinned to the bug's " (pr-str pinned)
(when (= expected actual)
". The expected value now holds: drop the pin in the fix commit"))))

View File

@ -21,6 +21,7 @@
[app.common.types.component :as ctk]
[app.common.types.container :as ctn]
[app.common.types.shape :as cts]
[app.common.types.shape.layout :as ctl]
[app.common.types.text :as txt]))
;; ----- File building
@ -85,6 +86,35 @@
(merge shape
child-params)))))
(defn add-grid-frame
[file frame-label & {:keys [] :as params}]
;; Generated shape tree:
;; :frame-label [:name Frame1 :layout :grid], with no rows, columns or cells
(add-frame file frame-label (merge {:layout :grid
:layout-grid-dir :row
:layout-grid-rows []
:layout-grid-columns []
:layout-grid-cells {}}
params)))
(defn place-in-grid-columns
"Give the grid frame `frame-label` one row and `columns` flex columns, and
put each child of it in `labels-by-column` (1-based column -> label) in
the cell of that column."
[file frame-label columns labels-by-column]
(let [frame (reduce (fn [frame _] (ctl/add-grid-column frame {:type :flex :value 1}))
(ctl/add-grid-row (ths/get-shape file frame-label) {:type :flex :value 1})
(range columns))
cells (reduce-kv (fn [cells column label]
(let [[id _] (d/seek #(= column (:column (val %))) cells)]
(assoc-in cells [id :shapes] [(thi/id label)])))
(:layout-grid-cells frame)
labels-by-column)]
(-> file
(ths/update-shape frame-label :layout-grid-rows (:layout-grid-rows frame))
(ths/update-shape frame-label :layout-grid-columns (:layout-grid-columns frame))
(ths/update-shape frame-label :layout-grid-cells cells))))
(defn add-minimal-component
[file component-label root-label
& {:keys [component-params root-params]}]

View File

@ -0,0 +1,70 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns app.common.test-helpers.normalize
"Normalized file values, to compare two states of a file in tests (the
undo/redo round trip of the composable runners, the golden master).
Normalizing drops only what legitimately differs between two states that
are the same for the user:
- `:modified-at` of the file and of each component, bumped by every
change, undo and redo included;
- with `{:position-data? false}`, the shapes' `:position-data`, the text
layout that WASM measurement regenerates.
Shapes and the maps that hold them become plain maps, so a shape record
compares equal to a map with the same attributes, and an objects map (see
`app.common.types.objects-map`) to a plain map with the same entries.
Everything else is kept, `:touched` and `:remote-synced` included."
(:require
[app.common.data :as d]
[clojure.data :as data]))
(defn- map-vals
"A plain map with `f` applied to each value of the map `m`, whatever its
type."
[f m]
(into {} (map (fn [[k v]] [k (f v)])) m))
(defn- normalize-shape
[shape {:keys [position-data?]}]
(cond-> (into {} shape)
(not position-data?) (dissoc :position-data)))
(defn- normalize-objects
[objects opts]
(map-vals #(normalize-shape % opts) objects))
(defn- normalize-page
[page opts]
(d/update-when page :objects normalize-objects opts))
(defn- normalize-component
[component opts]
(-> component
(dissoc :modified-at)
(d/update-when :objects normalize-objects opts)))
(defn normalize-file
"The normalized value of `file` (see the namespace doc). Options:
`:position-data?` (default true) keeps the shapes' `:position-data`."
([file] (normalize-file file {}))
([file opts]
(let [opts (merge {:position-data? true} opts)]
(-> file
(dissoc :modified-at)
(update :data
(fn [data]
(-> data
(d/update-when :pages-index
(partial map-vals #(normalize-page % opts)))
(d/update-when :components
(partial map-vals #(normalize-component % opts))))))))))
(defn diff
"What differs between the values `a` and `b`, as `[only-in-a only-in-b]`
(see `clojure.data/diff`)."
[a b]
(vec (take 2 (data/diff a b))))

View File

@ -860,6 +860,5 @@
(:id copy2-root-child2)
{:component-id [(thi/id :component1) (thi/id :wrong-comp3)]}}}}}}]
(thf/dump-file file') ;; Uncomment to debug
(t/is (= expected-diff diff)))))

View File

@ -0,0 +1,365 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns common-tests.files.repair-components-test
"One test per component error code of `app.common.files.validate`: each
builds a file broken in one way, checks the codes validation reports,
repairs it as the backend does (validate and repair until valid, at most
ten passes) and checks the result.
Three codes have no test because no file can produce them: the checks that
report `:component-not-main`, `:should-be-component-root` and
`:not-component-not-allowed` only run on shapes that already satisfy them."
(:require
[app.common.files.changes-builder :as pcb]
[app.common.files.repair :as cfr]
[app.common.files.validate :as cfv]
[app.common.logic.shapes :as cls]
[app.common.test-helpers.components :as thc]
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.compositions :as tho]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[app.common.types.component :as ctk]
[app.common.types.components-list :as ctkl]
[app.common.types.file :as ctf]
[app.common.uuid :as uuid]
[clojure.test :as t]))
(t/use-fixtures :each thi/test-fixture)
;; The backend repairs a file at most this many times (`app.srepl.procs.file-repair`).
(def ^:private max-passes 10)
(defn- codes
[errors]
(into #{} (map :code) errors))
(defn- repair
"Validate `file` and repair it until it validates, as the backend does.
Returns `[codes file' errors']`: the codes found first, the repaired file
and the errors left after the last pass (nil when it validates)."
([file] (repair file {}))
([file libraries]
(let [errors (cfv/validate-file file libraries)]
(loop [file file
errs errors
passes 0]
(if (or (nil? errs) (= passes max-passes))
[(codes errors) file errs]
(let [changes (cfr/repair-file file libraries errs)
file' (thf/apply-changes file {:redo-changes changes} :validate? false)]
(recur file' (cfv/validate-file file' libraries) (inc passes))))))))
;; ---- Configurations
(defn- simple
"A component (:main-root with :main-child) and a copy (:copy-root with
:copy-child)."
[& {:as params}]
(-> (thf/sample-file :file1 :page-label :page1)
(tho/add-simple-component-with-copy :component1 :main-root :main-child :copy-root
(merge {:copy-root-params {:children-labels [:copy-child]}}
params))))
(defn- nested
"Component2 (:main2-root) nests a copy of component1 (:main2-nested-head);
its copy :copy2-root holds :copy2-nested-head."
[]
(-> (thf/sample-file :file1 :page-label :page1)
(tho/add-nested-component-with-copy :component1 :main1-root :main1-child
:component2 :main2-root :main2-nested-head
:copy2-root
:copy2-root-params {:children-labels [:copy2-nested-head :copy2-child]})))
(defn- two-nested
"Component2 (:main2-root) nests two copies of component1 (:nested-a,
:nested-b); its copy :copy2-root holds their copies :copy-a and :copy-b."
[]
(let [file (-> (thf/sample-file :file1 :page-label :page1)
(tho/add-simple-component :component1 :main1-root :main1-child)
(tho/add-frame :main2-root)
(thc/instantiate-component :component1 :nested-a :parent-label :main2-root)
(thc/instantiate-component :component1 :nested-b :parent-label :main2-root)
(thc/make-component :component2 :main2-root)
(thc/instantiate-component :component2 :copy2-root))
objects (:objects (thf/current-page file))]
(doseq [[main-label copy-label] [[:nested-a :copy-a] [:nested-b :copy-b]]]
(thi/set-id! copy-label
(->> (get-in objects [(thi/id :copy2-root) :shapes])
(filter #(= (thi/id main-label) (get-in objects [% :shape-ref])))
(first))))
file))
(defn- reparent
"Move the shape `label` under the shape `parent-id`, keeping the links
consistent."
[file label parent-id]
(let [objects (:objects (thf/current-page file))
shape (get objects (thi/id label))
old-id (:parent-id shape)
parent (get objects parent-id)]
(-> file
(ths/update-shape-by-id old-id :shapes (filterv #(not= (:id shape) %) (:shapes (get objects old-id))))
(ths/update-shape-by-id parent-id :shapes (conj (vec (:shapes parent)) (:id shape)))
(ths/update-shape label :parent-id parent-id)
(ths/update-shape label :frame-id (if (= :frame (:type parent)) parent-id (:frame-id parent))))))
(defn- delete-main
"Delete the main `label`, which deletes its component."
[file label]
(let [page (thf/current-page file)
[_ changes] (cls/generate-delete-shapes (pcb/empty-changes nil (:id page))
file page (:objects page) #{(thi/id label)} {})]
(thf/apply-changes file changes :validate? false)))
(defn- update-deleted-object
"Apply `f` to the shape `label` stored in the deleted component
`component-label`."
[file component-label label f]
(ctf/update-file-data file
(fn [data]
(ctkl/update-component data (thi/id component-label)
#(update-in % [:objects (thi/id label)] f)))))
(defn- deleted-object
[file component-label label]
(get-in (ctkl/get-component (:data file) (thi/id component-label) true)
[:objects (thi/id label)]))
(defn- slot-group
[id]
#{(ctk/build-swap-slot-group id)})
;; ---- Main heads
(t/deftest component-main-external
;; the main points at a library that also has its component
(let [file (ths/update-shape (simple) :main-root :component-file (thi/new-id! :library))
library (assoc file :id (thi/id :library))
[found file' errors] (repair file {(:id library) library})]
(t/is (= #{:component-main-external} found))
(t/is (nil? errors))
(t/is (= (thi/id :file1) (:component-file (ths/get-shape file' :main-root))))))
(t/deftest component-not-found
(let [[found file' errors] (repair (ths/update-shape (simple) :copy-root :component-id (uuid/next)))]
(t/is (= #{:component-not-found :ref-shape-not-found} found))
(t/is (nil? errors))
;; the copy is detached
(t/is (nil? (:component-id (ths/get-shape file' :copy-root))))))
(t/deftest invalid-main-instance-id
(let [[found file' errors] (repair (thc/update-component (simple) :component1 :main-instance-id (uuid/next)))]
(t/is (= #{:invalid-main-instance-id :ref-shape-not-found} found))
(t/is (nil? errors))
(t/is (= (thi/id :main-root) (:main-instance-id (thc/get-component file' :component1))))))
(t/deftest invalid-main-instance-page
(let [file (-> (simple)
(thf/add-sample-page :page2)
(thf/switch-to-page :page1)
(thc/update-component :component1 :main-instance-page (thi/id :page2)))
[found file' errors] (repair file)]
(t/is (= #{:invalid-main-instance-page :ref-shape-not-found} found))
(t/is (nil? errors))
(t/is (= (thi/id :page1) (:main-instance-page (thc/get-component file' :component1))))))
(t/deftest invalid-main-instance
;; the component names the copy as its main; the repair of
;; :invalid-main-instance does nothing, the main's own error fixes it
(let [[found file' errors] (repair (thc/update-component (simple) :component1 :main-instance-id (thi/id :copy-root)))]
(t/is (= #{:invalid-main-instance :invalid-main-instance-id :ref-shape-not-found} found))
(t/is (nil? errors))
(t/is (= (thi/id :main-root) (:main-instance-id (thc/get-component file' :component1))))))
(t/deftest shape-ref-in-main
(let [[found file' errors] (repair (ths/update-shape (simple) :main-root :shape-ref (thi/id :copy-root)))]
(t/is (= #{:shape-ref-in-main} found))
(t/is (nil? errors))
(t/is (nil? (:shape-ref (ths/get-shape file' :main-root))))))
;; ---- Shapes inside mains
(t/deftest component-main-flag-on-a-child
(let [[found file' errors] (repair (ths/update-shape (simple) :main-child :main-instance true))]
(t/is (= #{:component-main} found))
(t/is (nil? errors))
(t/is (nil? (:main-instance (ths/get-shape file' :main-child))))))
(t/deftest component-main-file-on-a-child
;; the repair only removes :main-instance, so the error never goes away
(let [[found _ errors] (repair (ths/update-shape (simple) :main-child :component-file (thi/id :file1)))]
(t/is (= #{:component-main} found))
(tm/known-failure "F47" nil #{:component-main} (codes errors))))
(t/deftest should-not-be-component-root
(let [[found file' errors] (repair (ths/update-shape (simple) :main-child :component-root true))]
(t/is (= #{:should-not-be-component-root} found))
(t/is (nil? errors))
(t/is (nil? (:component-root (ths/get-shape file' :main-child))))))
(t/deftest not-head-main-not-allowed
;; a main root without component is no longer a head; repair detaches the
;; main and then its copy
(let [[found file' errors] (repair (ths/update-shape (simple) :main-root :component-id nil))]
(t/is (= #{:not-head-main-not-allowed :ref-shape-is-not-head} found))
(t/is (nil? errors))
(t/is (nil? (:main-instance (ths/get-shape file' :main-root))))
(t/is (nil? (:shape-ref (ths/get-shape file' :copy-root))))))
;; ---- Copies
(t/deftest ref-shape-not-found
(let [[found file' errors] (repair (ths/update-shape (nested) :copy2-nested-head :shape-ref (uuid/next)))]
(t/is (= #{:ref-shape-not-found :missing-slot} found))
(t/is (nil? errors))
;; no matching shape: the nested copy is detached
(t/is (nil? (:shape-ref (ths/get-shape file' :copy2-nested-head))))))
(t/deftest ref-shape-not-found-in-a-copy-child
;; the reference of a non-head copy shape is never checked: the check reads
;; the library from the shape itself, and only heads have one
(let [errors (cfv/validate-file (ths/update-shape (simple) :copy-child :shape-ref (uuid/next)) {})]
(tm/known-failure "F46" #{:ref-shape-not-found} #{} (codes errors))))
(t/deftest ref-shape-is-head
;; the check reports no component, so the repair cannot make the shape a
;; head again
(let [file (-> (nested)
(ths/update-shape :copy2-nested-head :component-id nil)
(ths/update-shape :copy2-nested-head :component-file nil))
[found _ errors] (repair file)]
(t/is (= #{:ref-shape-is-head} found))
(tm/known-failure "F48" nil #{:ref-shape-is-head} (codes errors))))
(t/deftest ref-shape-is-not-head
;; a copy child made a head while the shape it references is not one
(let [file (-> (simple :main-child-params {:type :frame})
(ths/update-shape :copy-child :component-id (thi/id :component1))
(ths/update-shape :copy-child :component-file (thi/id :file1)))
[found file' errors] (repair file)]
(t/is (= #{:ref-shape-is-not-head :component-id-mismatch} found))
(t/is (nil? errors))
(t/is (not (ctk/instance-head? (ths/get-shape file' :copy-child))))))
(t/deftest component-id-mismatch
(let [[found file' errors] (repair (ths/update-shape (nested) :copy2-nested-head :component-id (thi/id :component2)))]
(t/is (= #{:component-id-mismatch} found))
(t/is (nil? errors))
(t/is (= (thi/id :component1) (:component-id (ths/get-shape file' :copy2-nested-head))))))
(t/deftest not-head-copy-not-allowed
(let [[found file' errors] (repair (reparent (simple) :copy-child uuid/zero))]
(t/is (= #{:not-head-copy-not-allowed} found))
(t/is (nil? errors))
(t/is (nil? (:shape-ref (ths/get-shape file' :copy-child))))))
(t/deftest instance-head-not-frame
(let [[found file' errors] (repair (ths/update-shape (simple) :copy-root :type :rect))]
(t/is (= #{:instance-head-not-frame} found))
(t/is (nil? errors))
(t/is (= :frame (:type (ths/get-shape file' :copy-root))))))
(t/deftest invalid-text-touched
(let [[found file' errors] (repair (ths/update-shape (simple) :copy-child :touched #{:text-content-text}))]
(t/is (= #{:invalid-text-touched} found))
(t/is (nil? errors))
(t/is (contains? (:touched (ths/get-shape file' :copy-child)) :content-group))))
;; ---- Nesting
(t/deftest root-main-not-allowed
(let [file (-> (simple)
(tho/add-simple-component :component2 :main2-root :main2-child)
(reparent :main-root (thi/id :main2-root)))
[found file' errors] (repair file)
main (ths/get-shape file' :main-root)]
(t/is (= #{:root-main-not-allowed :nested-main-not-allowed} found))
(t/is (nil? errors))
;; moved back to the page root, as a top main
(t/is (= uuid/zero (:parent-id main)))
(t/is (true? (:component-root main)))))
(t/deftest nested-main-not-allowed
(let [[found file' errors] (repair (ths/update-shape (simple) :main-root :component-root nil))]
(t/is (= #{:nested-main-not-allowed} found))
(t/is (nil? errors))
(t/is (true? (:component-root (ths/get-shape file' :main-root))))))
(t/deftest root-copy-not-allowed
(let [[found file' errors] (repair (reparent (simple) :copy-root (thi/id :main-root)))]
(t/is (= #{:root-copy-not-allowed} found))
(t/is (nil? errors))
;; it stays in the main, as a nested copy
(t/is (nil? (:component-root (ths/get-shape file' :copy-root))))))
(t/deftest nested-copy-not-allowed
(let [[found file' errors] (repair (ths/update-shape (simple) :copy-root :component-root nil))]
(t/is (= #{:nested-copy-not-allowed} found))
(t/is (nil? errors))
(t/is (true? (:component-root (ths/get-shape file' :copy-root))))))
;; ---- Components
(t/deftest component-nil-objects-not-allowed
(let [[found file' errors] (repair (thc/update-component (simple) :component1 :objects nil))]
(t/is (= #{:component-nil-objects-not-allowed} found))
(t/is (nil? errors))
(t/is (not (contains? (thc/get-component file' :component1) :objects)))))
(t/deftest non-deleted-component-cannot-have-objects
(let [[found file' errors] (repair (thc/update-component (simple) :component1 :objects {(uuid/next) {}}))]
(t/is (= #{:non-deleted-component-cannot-have-objects} found))
(t/is (nil? errors))
(t/is (not (contains? (thc/get-component file' :component1) :objects)))))
(t/deftest shape-ref-cycle
(let [file (-> (two-nested)
(delete-main :main2-root)
(update-deleted-object :component2 :nested-a #(assoc % :shape-ref (:id %))))
[found file' errors] (repair file)]
(t/is (= #{:shape-ref-cycle} found))
(t/is (nil? errors))
(t/is (not= (thi/id :nested-a) (:shape-ref (deleted-object file' :component2 :nested-a))))))
;; ---- Swap slots
(t/deftest misplaced-slot
(let [[found file' errors] (repair (ths/update-shape (simple) :copy-root :touched (slot-group (uuid/next))))]
(t/is (= #{:misplaced-slot} found))
(t/is (nil? errors))
(t/is (nil? (ctk/get-swap-slot (ths/get-shape file' :copy-root))))))
(t/deftest duplicate-slot
(let [file (-> (two-nested)
(ths/update-shape :copy-a :touched (slot-group (thi/id :nested-a)))
(ths/update-shape :copy-b :touched (slot-group (thi/id :nested-a))))
[found file' errors] (repair file)]
(t/is (= #{:duplicate-slot} found))
(t/is (nil? errors))
(t/is (nil? (ctk/get-swap-slot (ths/get-shape file' :copy-b))))))
(t/deftest component-duplicate-slot
(let [file (-> (two-nested)
(delete-main :main2-root)
(update-deleted-object :component2 :nested-a #(assoc % :touched (slot-group (thi/id :nested-a))))
(update-deleted-object :component2 :nested-b #(assoc % :touched (slot-group (thi/id :nested-a)))))
[found file' errors] (repair file)]
(t/is (= #{:component-duplicate-slot} found))
(t/is (nil? errors))
(t/is (nil? (ctk/get-swap-slot (deleted-object file' :component2 :nested-b))))))
(t/deftest missing-slot
(let [file (-> (two-nested)
(tho/add-simple-component :component3 :main3-root :main3-child)
(tho/swap-component-in-shape :copy-a :component3 :new-shape-label :swapped)
(ths/update-shape :swapped :touched nil))
[found file' errors] (repair file)]
(t/is (= #{:missing-slot} found))
(t/is (nil? errors))
(t/is (= (thi/id :nested-a) (ctk/get-swap-slot (ths/get-shape file' :swapped))))))

View File

@ -20,6 +20,7 @@
[app.common.types.component :as ctk]
[app.common.types.components-list :as ctkl]
[app.common.types.file :as ctf]
[app.common.types.pages-list :as ctpl]
[app.common.types.shape-tree :as ctst]
[app.common.uuid :as uuid]
[clojure.test :as t]))
@ -459,6 +460,59 @@
(t/is (ctk/main-instance-of? (:id main1-root') (:id page) component1'))
(t/is (nil? saved-objects'))))
(defn- restore-after-page-deletion
"Delete :component1, whose main lives on :page-2, then delete that page,
and restore the component from `current-page`. Returns the restored
file."
[file current-page]
(let [page2 (thf/get-page file :page-2)
root (ths/get-shape file :main1-root :page-label :page-2)
[_ changes] (cls/generate-delete-shapes (pcb/empty-changes)
file
page2
(:objects page2)
#{(:id root)}
{:components-v2 true})
file (-> (thf/apply-changes file changes)
(ctf/update-file-data #(ctpl/delete-page % (:id page2))))
changes (cll/generate-restore-component (pcb/empty-changes)
(:data file)
(thi/id :component1)
(:id file)
current-page
(:objects current-page))]
(thf/apply-changes file changes)))
(defn- three-page-file
"A file with pages :page-1, :page-2 (holding the main of :component1) and
:page-3."
[]
(-> (thf/sample-file :file1 :page-label :page-1)
(thf/add-sample-page :page-2)
(tho/add-simple-component :component1 :main1-root :main1-child)
(thf/add-sample-page :page-3)
(thf/switch-to-page :page-1)))
(t/deftest test-restore-component-whose-page-was-deleted
(let [file (three-page-file)
file' (restore-after-page-deletion file (thf/get-page file :page-1))
comp' (thc/get-component file' :component1 :include-deleted? false)]
;; the current page belongs to the library, so the main goes there
(t/is (some? comp'))
(t/is (= (thi/id :page-1) (:main-instance-page comp')))
(t/is (some? (get-in (thf/get-page file' :page-1) [:objects (:main-instance-id comp')])))))
(t/deftest test-restore-component-from-a-page-of-another-file
(let [file (three-page-file)
other (thf/sample-page :other-page)
file' (restore-after-page-deletion file other)
comp' (thc/get-component file' :component1 :include-deleted? false)]
;; the current page is not one of the library's, so the main goes to
;; the library's last page
(t/is (some? comp'))
(t/is (= (thi/id :page-3) (:main-instance-page comp')))
(t/is (some? (get-in (thf/get-page file' :page-3) [:objects (:main-instance-id comp')])))))
(t/deftest test-instantiate-component
(let [;; ==== Setup
file (-> (thf/sample-file :file1)

View File

@ -133,7 +133,6 @@
;; ==== Check
;; It should the same as above, but in an external library.
(thf/dump-file file)
(t/is (ctk/instance-root? copy-h-board-with-ellipse))
(t/is (= (:shape-ref copy-h-board-with-ellipse) (thi/id :board-with-ellipse)))
(t/is (nil? (ctk/get-swap-slot copy-h-board-with-ellipse)))

View File

@ -11,6 +11,7 @@
[app.common.test-helpers.composable.comp.nodes :as n]
[app.common.test-helpers.composable.comp.runner :as r]
[app.common.test-helpers.composable.comp.setups :as setup]
[app.common.test-helpers.composable.comp.undo-check :as uc]
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
@ -19,7 +20,7 @@
(t/use-fixtures :each thi/test-fixture)
(def ^:private original "#abcdef")
(def ^:private original setup/labeled-fill)
(def ^:private red "#ff0000")
(def ^:private green "#00ff00")
@ -27,14 +28,6 @@
[shape]
(-> shape :fills first :fill-color))
(t/deftest main-edit-syncs-to-clean-copy
(let [situation (r/run-variant
{:setup setup/simple-component-with-labeled-copy
:operation (n/change-property :main-child :fills red)})
copy (setup/copy-instance situation)]
(t/is (= red (fill-of copy)))
(t/is (nil? (:touched copy)))))
(t/deftest main-edit-without-sync-leaves-copy-stale
(let [situation (r/run-variant
{:setup setup/simple-component-with-labeled-copy
@ -43,16 +36,6 @@
(t/is (= red (fill-of (setup/main-instance situation))))
(t/is (= original (fill-of (setup/copy-instance situation))))))
(t/deftest copy-override-survives-main-edit
(let [situation (r/run-variant
{:setup setup/simple-component-with-labeled-copy
:operation (tm/in-sequence
[(n/change-property :copy-child :fills green)
(n/change-property :main-child :fills red)])})
copy (setup/copy-instance situation)]
(t/is (= green (fill-of copy)))
(t/is (contains? (:touched copy) :fill-group))))
(t/deftest sync-cascades-through-nested-components
;; The edit is on the deepest main. Its copy inside the outer main changes,
;; so the outer component syncs in a second pass and reaches the outer copy.
@ -120,6 +103,64 @@
(t/is (contains? (:touched copy-rect) :fill-group))
(t/is (= 1 (r/undo-depth situation)))))
(t/deftest redo-reapplies-edit-and-its-sync
(let [situation (r/run-variant
{:setup setup/simple-component-with-labeled-copy
:operation (tm/in-sequence
[(n/change-property :main-child :fills red)
(n/undo)
(n/redo)])})
copy (setup/copy-instance situation)]
(t/is (= red (fill-of (setup/main-instance situation))))
(t/is (= red (fill-of copy)))
(t/is (nil? (:touched copy)))
(t/is (= 1 (r/undo-depth situation)))
(t/is (zero? (r/redo-depth situation)))))
(t/deftest redo-reapplies-groups-in-undo-order
(let [situation (r/run-variant
{:setup setup/simple-component-with-labeled-copy
:operation (tm/in-sequence
[(n/change-property :main-child :fills red)
(n/change-property :main-child :fills green)
(n/undo)
(n/undo)
(n/redo)])})]
(t/is (= red (fill-of (setup/copy-instance situation))))
(t/is (= 1 (r/undo-depth situation)))
(t/is (= 1 (r/redo-depth situation)))))
(t/deftest user-operation-empties-the-redo-stack
(let [situation (r/run-variant
{:setup setup/simple-component-with-labeled-copy
:operation (tm/in-sequence
[(n/change-property :main-child :fills red)
(n/undo)
(n/change-property :main-child :fills green)
(n/redo)])})]
(t/is (= green (fill-of (setup/copy-instance situation))))
(t/is (= 1 (r/undo-depth situation)))
(t/is (zero? (r/redo-depth situation)))))
(t/deftest unchanged-user-operation-keeps-the-redo-stack
(let [situation (r/run-variant
{:setup setup/simple-component-with-labeled-copy
:operation (tm/in-sequence
[(n/change-property :main-child :fills red)
(n/undo)
(n/change-property :main-child :fills original)
(n/redo)])})]
(t/is (= red (fill-of (setup/copy-instance situation))))))
(t/deftest redo-with-an-empty-stack-changes-nothing
(let [situation (r/run-variant
{:setup setup/simple-component-with-labeled-copy
:operation (tm/in-sequence
[(n/change-property :main-child :fills red)
(n/redo)])})]
(t/is (= red (fill-of (setup/copy-instance situation))))
(t/is (= 1 (r/undo-depth situation)))))
(t/deftest assembly-operations-push-no-undo-group
(let [m "main"
situation (r/run-variant
@ -131,13 +172,6 @@
(t/is (zero? (r/undo-depth situation)))
(t/is (some? (tm/shape-by-id situation (n/lineage-copy-rect situation m))))))
(t/deftest added-child-reaches-copy
(let [add (n/add-child :main-root :new-child)
situation (r/run-variant
{:setup setup/simple-component-with-copy
:operation add})]
(t/is (some? (n/materialized-instance-child add situation (setup/copy-root situation))))))
(t/deftest undo-removes-added-child-from-main-and-copy
(let [situation (r/run-variant
{:setup setup/simple-component-with-copy
@ -260,3 +294,149 @@
(n/switch-variant (n/nested-head-of m 0) "a")])})]
(t/is (= original (level-fill situation m 0)))
(t/is (zero? (r/undo-depth situation)))))
;; A user operation that changes the opacity of the copy root and whose
;; undo changes also rename it.
(defrecord WrongUndoEdit []
n/IComponentOperation
(op-kind [_] :user)
tm/IOperation
(apply-to [this situation]
(let [file (tm/file situation)
page (thf/current-page file)
changes (cls/generate-update-shapes (pcb/empty-changes nil (:id page))
#{(:id (setup/copy-root situation))}
#(assoc % :opacity 0.5)
(:objects page)
{})
changes (update changes :undo-changes
(partial mapv #(cond-> %
(= :mod-obj (:type %))
(update :operations conj {:type :set
:attr :name
:val "Wrong"
:ignore-touched true
:ignore-geometry false}))))]
(-> situation
(tm/with-file (thf/apply-changes file changes))
(n/record-changes changes)
(tm/record-application this {})))))
;; A user operation that changes the file with no undo changes.
(defrecord EditWithoutUndo []
n/IComponentOperation
(op-kind [_] :user)
tm/IOperation
(apply-to [this situation]
(let [file (tm/file situation)
page (thf/current-page file)
changes (-> (cls/generate-update-shapes (pcb/empty-changes nil (:id page))
#{(:id (setup/copy-root situation))}
#(assoc % :opacity 0.5)
(:objects page)
{})
(assoc :undo-changes []))]
(-> situation
(tm/with-file (thf/apply-changes file changes))
(n/record-changes changes)
(tm/record-application this {})))))
(defn- phases
[situation]
(mapv :phase (uc/failures situation)))
(t/deftest round-trip-passes-for-exact-inverses
(let [situation (r/run-variant
{:setup setup/simple-component-with-labeled-copy
:operation (tm/in-sequence
[(n/change-property :copy-child :fills green)
(n/change-property :main-child :fills red)
(n/undo)
(n/redo)])})]
(t/is (empty? (uc/failures situation)))
(t/is (= red (fill-of (setup/main-instance situation))))))
(t/deftest round-trip-reports-a-wrong-undo
(let [situation (r/run-variant {:setup setup/simple-component-with-copy
:operation (->WrongUndoEdit)})]
;; the redo leaves the wrong name in place, and so does the variant undo
(t/is (= [:undo :redo :variant-undo] (phases situation)))
(t/is (= (repeat 3 #{[:object :copy-root :name]})
(map :signature (uc/failures situation))))
(t/is (= {:name "Wrong"}
(-> (uc/failures situation) first :diff second :data :pages-index
vals first :objects (get :copy-root))))))
(t/deftest round-trip-reports-a-change-with-no-undo-entry
(let [situation (r/run-variant {:setup setup/simple-component-with-copy
:operation (->EditWithoutUndo)})]
(t/is (= [:no-undo-entry] (phases situation)))))
(t/deftest round-trip-can-be-turned-off
(let [situation (r/run-variant {:setup setup/simple-component-with-copy
:operation (->EditWithoutUndo)
:undo-check {:off "testing the switch"}})]
(t/is (empty? (uc/failures situation)))))
(t/deftest round-trip-never-undoes-past-an-assembly-step
;; The edit before the copy exists is not undone at the end of the variant,
;; so the main keeps it.
(let [m "main"
situation (r/run-variant
{:setup setup/empty-situation
:operation (tm/in-sequence
[(n/create-component m original)
(n/change-property (n/main-rect-of m) :fills red)
(n/instantiate-copy m)
(n/change-property (n/copy-rect-of m) :fills green)])})]
(t/is (empty? (uc/failures situation)))
(t/is (= red (fill-of (tm/shape-by-id situation (n/lineage-rect situation m)))))))
(t/deftest signature-names-what-differs
(let [shape {:id (thi/new-id! :shape) :name "A" :opacity 1}
other {:id (thi/new-id! :other) :name "B"}
page-id (thi/new-id! :page)
file (fn [objects] {:data {:pages-index {page-id {:id page-id :objects objects}}}})]
(t/is (= #{[:object :shape :opacity] [:object :other :extra]}
(uc/signature (file {(:id shape) shape})
(file {(:id shape) (assoc shape :opacity 0.5)
(:id other) other}))))
(t/is (= #{[:object :unlabelled :missing]}
(uc/signature (file {(uuid/next) shape}) (file {}))))))
(t/deftest known-failures-pin-how-the-check-fails
(let [edit (tm/assign-id (->WrongUndoEdit))
situation (r/run-variant {:setup setup/simple-component-with-copy
:operation edit})
pin #{[:object :copy-root :name]}
known {:bug "F0" :fails {:undo pin :redo pin :variant-undo pin} :op edit}
verdict #(uc/verdict situation {:undo-check {:known-failures %}})]
(t/is (= {:unexpected [] :resolved []} (verdict [known])))
(t/is (= [:undo :redo :variant-undo]
(mapv :phase (:unexpected (uc/verdict situation {})))))
(t/testing "a failure that differs from its pin stays a failure"
(let [{:keys [unexpected resolved]}
(verdict [(assoc-in known [:fails :undo] #{[:object :copy-root :opacity]})])]
(t/is (= [:undo] (mapv :phase unexpected)))
(t/is (= [:undo] (mapv :phase resolved)))))
(t/testing "a pinned phase that does not fail is resolved"
(t/is (= [:variant-redo]
(mapv :phase (:resolved (verdict [(assoc-in known [:fails :variant-redo] pin)]))))))
(t/testing "a mark applies only where its step ran and its runner runs"
(t/is (= [] (:resolved (verdict [known (assoc known :op (tm/assign-id (->WrongUndoEdit)))]))))
(t/is (= [] (:resolved (verdict [known (assoc known :runners #{:frontend} :op nil)])))))
(t/testing "a mark must pin its failures"
(t/is (thrown? #?(:clj Exception :cljs :default)
(verdict [(dissoc known :fails)]))))))
(t/deftest known-failure-holds-only-the-pinned-value
(let [reports (fn [actual]
(let [types (atom [])]
(binding [t/report #(swap! types conj (:type %))]
(tm/known-failure "F0" :right :wrong actual))
@types))]
(t/is (= [:pass] (reports :wrong)))
(t/is (= [:fail] (reports :right)))
(t/is (= [:fail] (reports :other)))))

View File

@ -6,11 +6,13 @@
(ns common-tests.logic.composable-sync-test
"Runs the shared composable component cases through the pure runner, on the
JVM and in JS. Case N and the rotation case need the frontend placement
step, so only the frontend interpreter runs them."
JVM and in JS. The geometry cases (N, Z, AI and the rotation case) need
the frontend placement step and case X a pending frontend sync, so only
the frontend interpreter runs them."
(:require
[app.common.test-helpers.composable.comp.cases :as cases]
[app.common.test-helpers.composable.comp.runner :as r]
[app.common.test-helpers.composable.comp.undo-check :as uc]
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.ids-map :as thi]
[clojure.test :as t]))
@ -18,12 +20,14 @@
(t/use-fixtures :each thi/test-fixture)
(defn- check
"Run every variant of `case-map` and apply its asserter to each result."
"Run every variant of `case-map`, apply its asserter to each result and
assert that its undo/redo round trip passed."
[{:keys [asserter] :as case-map}]
(doseq [situation (r/run-all case-map)]
(when asserter
(t/testing (str "operations:\n " (tm/describe-applied situation))
(asserter situation)))))
(t/testing (str "operations:\n " (tm/describe-applied situation))
(when asserter
(asserter situation))
(uc/check! situation case-map))))
(t/deftest case-b-copy-override-survives-later-main-change
(check (cases/copy-override-survives-later-main-change)))
@ -46,6 +50,9 @@
(t/deftest case-i-undo-reverts-edit-and-its-propagation
(check (cases/undo-reverts-edit-and-its-propagation)))
(t/deftest case-p-redo-reapplies-edit-and-its-propagation
(check (cases/redo-reapplies-edit-and-its-propagation)))
(t/deftest case-k-synchronisation-scenarios
(check (cases/synchronisation-scenarios)))
@ -57,3 +64,84 @@
(t/deftest case-o-variant-switch-keeps-override-only-where-mains-agree
(check (cases/variant-switch-keeps-override-only-where-mains-agree)))
(t/deftest case-q-detach-keeps-nested-copies-linked
(check (cases/detach-keeps-nested-copies-linked)))
(t/deftest case-r-update-main-reaches-other-copies
(check (cases/update-main-reaches-other-copies)))
(t/deftest case-s-deleted-component-copies-sync-again-after-restore
(check (cases/deleted-component-copies-sync-again-after-restore)))
(t/deftest case-t-duplicated-copy-keeps-overrides-and-link
(check (cases/duplicated-copy-keeps-overrides-and-link)))
(t/deftest case-u-nested-copy-reaches-copies-of-the-receiving-main
(check (cases/nested-copy-reaches-copies-of-the-receiving-main)))
(t/deftest case-v-new-edit-after-undo-clears-redo
(check (cases/new-edit-after-undo-clears-redo)))
(t/deftest case-w-undo-several-steps-over-nested-cascades
(check (cases/undo-several-steps-over-nested-cascades)))
(t/deftest case-y-text-override-merges-with-main-text-change
(check (cases/text-override-merges-with-main-text-change)))
(t/deftest case-aa-copy-swap-survives-main-changes
(check (cases/copy-swap-survives-main-changes)))
(t/deftest case-ab-reset-of-nested-swap-keeps-top-copy-overrides
(check (cases/reset-of-nested-swap-keeps-top-copy-overrides)))
(t/deftest case-ac-second-variant-switch-keeps-root-overrides
(check (cases/second-variant-switch-keeps-root-overrides)))
(t/deftest case-ad-update-main-pushes-a-swapped-child
(check (cases/update-main-pushes-a-swapped-child)))
(t/deftest case-ae-detached-or-duplicated-swapped-copy-follows-its-component
(check (cases/detached-or-duplicated-swapped-copy-follows-its-component)))
(t/deftest case-af-grid-cell-move-reaches-a-swapped-copy-child
(check (cases/grid-cell-move-reaches-a-swapped-copy-child)))
(t/deftest case-ag-main-reorder-keeps-copy-sub-heads-aligned
(check (cases/main-reorder-keeps-copy-sub-heads-aligned)))
(t/deftest case-ah-copy-sub-head-delete-keeps-others-aligned
(check (cases/copy-sub-head-delete-keeps-others-aligned)))
(t/deftest case-ak-update-main-pushes-grid-cells
(check (cases/update-main-pushes-grid-cells)))
(t/deftest case-al-update-main-renames-the-component
(check (cases/update-main-renames-the-component)))
(t/deftest case-am-update-main-pushes-a-swap-inside-a-group
(check (cases/update-main-pushes-a-swap-inside-a-group)))
(t/deftest case-an-flex-child-override-follows-sync-reset-and-update-main
(check (cases/flex-child-override-follows-sync-reset-and-update-main)))
(t/deftest case-ao-copy-dropped-into-a-grid-cell-reaches-copies
(check (cases/copy-dropped-into-a-grid-cell-reaches-copies)))
(t/deftest case-ap-library-main-child-removal-reaches-copy
(check (cases/library-main-child-removal-reaches-copy)))
(t/deftest case-aq-main-change-reaches-a-copy-nested-in-a-sub-board
(check (cases/main-change-reaches-a-copy-nested-in-a-sub-board)))
(t/deftest case-ar-variant-property-edits-keep-copies
(check (cases/variant-property-edits-keep-copies)))
(t/deftest case-as-added-variant-is-a-switch-target
(check (cases/added-variant-is-a-switch-target)))
(t/deftest case-ay-token-on-a-main-reaches-copies
(check (cases/token-on-a-main-reaches-copies)))
(t/deftest case-az-copy-moved-out-of-its-main-keeps-inherited-overrides
(check (cases/copy-moved-out-of-its-main-keeps-inherited-overrides)))

View File

@ -0,0 +1,147 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns common-tests.logic.library-asset-sync-test
"Library color and typography sync in component copies. The sync writes
the asset's new value into every shape that uses it, copies included.
That write is derived from the library, not authored on the copy, so it
must not touch the copy (`mem:common/component-sync-contract`), and later
main edits must still reach it."
(:require
[app.common.files.changes-builder :as pcb]
[app.common.logic.libraries :as cll]
[app.common.logic.shapes :as cls]
[app.common.test-helpers.components :as thc]
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.compositions :as tho]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[app.common.types.text :as txt]
[app.common.types.typographies-list :as cttl]
[clojure.test :as t]))
(t/use-fixtures :each thi/test-fixture)
(defn- sync-file
"Apply the sync of `asset-type` (`:colors`, `:typographies` or
`:components`) for `asset-id` from the file to itself."
[file asset-type asset-id]
(let [changes (cll/generate-sync-file-changes (pcb/empty-changes)
nil
asset-type
(:id file)
asset-id
(:id file)
{(:id file) file}
(:id file))]
(thf/apply-changes file changes)))
(defn- update-shape
"Change the shape `label` with `f` through the production change path."
[file label f]
(let [page (thf/current-page file)
changes (cls/generate-update-shapes (pcb/empty-changes nil (:id page))
#{(thi/id label)}
f
(:objects page)
{})]
(thf/apply-changes file changes)))
;; ---- Colors
(defn- color-fill
[color]
{:fill-color color
:fill-opacity 1
:fill-color-ref-id (thi/id :color1)
:fill-color-ref-file (thi/id :file1)})
(defn- component-using-color
"A component whose child is filled with the library color :color1
(#111111), and a copy of it."
[]
(-> (thf/sample-file :file1)
(ths/add-sample-library-color :color1 :color "#111111")
(tho/add-simple-component-with-copy :component1 :main-root :main-child :copy-root
:main-child-params {:fills [(color-fill "#111111")]}
:copy-root-params {:children-labels [:copy-child]})))
(defn- change-library-color
[file color]
(-> file
(assoc-in [:data :colors (thi/id :color1) :color] color)
(sync-file :colors (thi/id :color1))))
(t/deftest library-color-sync-reaches-the-copy-untouched
(let [file' (change-library-color (component-using-color) "#222222")
copy (ths/get-shape file' :copy-child)]
(t/is (= "#222222" (-> copy :fills first :fill-color)))
;; the sync writes the fill without ignore-touched
(tm/known-failure "F3" nil #{:fill-group} (:touched copy))))
(t/deftest main-fill-edit-reaches-the-copy-after-a-library-color-sync
(let [file' (-> (component-using-color)
(change-library-color "#222222")
(sync-file :components (thi/id :component1))
(update-shape :main-child #(assoc % :fills (ths/sample-fills-color :fill-color "#333333")))
(sync-file :components (thi/id :component1)))]
;; the touched fill blocks it
(tm/known-failure "F3" "#333333" "#222222" (-> (ths/get-shape file' :copy-child) :fills first :fill-color))))
;; ---- Typographies
(defn- typography-text
"A text \"hello\" styled, on every node, with the library typography
:typography1, as applying a typography in the app does."
[font-size]
(-> (txt/change-text (:content (ths/sample-shape :tmp :type :text)) "hello")
(->> (txt/transform-nodes txt/is-content-node?
#(assoc %
:font-size font-size
:typography-ref-id (thi/id :typography1)
:typography-ref-file (thi/id :file1))))))
(defn- component-using-typography
"A component whose child is a text styled with the library typography
:typography1 (font size 14), and a copy of it."
[]
(-> (thf/sample-file :file1)
(ths/add-sample-typography :typography1 :font-size "14")
(tho/add-frame-with-text :main-root :main-child "hello"
:child-params {:content (typography-text "14")})
(thc/make-component :component1 :main-root)
(thc/instantiate-component :component1 :copy-root :children-labels [:copy-child])))
(defn- font-size-of
"The font size of the first span of the text `shape`."
[shape]
(get-in shape [:content :children 0 :children 0 :children 0 :font-size]))
(defn- change-library-typography
[file font-size]
(-> file
(update :data cttl/update-typography (thi/id :typography1) assoc :font-size font-size)
(sync-file :typographies (thi/id :typography1))))
(t/deftest library-typography-sync-reaches-the-copy-untouched
(let [file' (change-library-typography (component-using-typography) "24")
copy (ths/get-shape file' :copy-child)]
(t/is (= "24" (font-size-of copy)))
;; the sync writes the content with a raw :set, which touches it
(tm/known-failure "F3" nil #{:content-group :text-content-attribute} (:touched copy))))
(t/deftest main-font-edit-reaches-the-copy-after-a-library-typography-sync
(let [file' (-> (component-using-typography)
(change-library-typography "24")
(sync-file :components (thi/id :component1))
(update-shape :main-child
(fn [shape]
(update shape :content
#(txt/transform-nodes txt/is-content-node? (fn [node] (assoc node :font-size "40")) %))))
(sync-file :components (thi/id :component1)))]
;; the touched text attributes block it
(tm/known-failure "F3" "40" "24" (font-size-of (ths/get-shape file' :copy-child)))))

View File

@ -10,6 +10,7 @@
[app.common.logic.libraries :as cll]
[app.common.logic.shapes :as cls]
[app.common.test-helpers.components :as thc]
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.compositions :as tho]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
@ -879,3 +880,50 @@
(t/is (= "14" (:font-size line)))
;; The text doesn't change, because the structure was touched
(t/is (= "hello world" (:text line)))))
(t/deftest sync-copy-touched-only-in-content-group
;; A copy text whose `:touched` has `:content-group` but no text subgroup,
;; as files from before the subgroups hold it, keeps its own content
;; when the main changes.
(let [;; ==== Setup
file (-> (thf/sample-file :file1)
(tho/add-frame-with-text :main-root :main-child "hello world")
(thc/make-component :component1 :main-root)
(thc/instantiate-component :component1 :copy-root {:children-labels [:copy-child]}))
copy-child (ths/get-shape file :copy-child)
file (-> file
(ths/update-shape :copy-child :content
(assoc-in (:content copy-child)
[:children 0 :children 0 :children 0 :text]
"copy text"))
(ths/update-shape :copy-child :touched #{:content-group}))
page (thf/current-page file)
;; ==== Action
changes1 (cls/generate-update-shapes (pcb/empty-changes nil (:id page))
#{(thi/id :main-child)}
(fn [shape]
(assoc-in shape [:content :children 0 :children 0 :children 0 :font-size] "32"))
(:objects page)
{})
updated-file (thf/apply-changes file changes1)
changes2 (cll/generate-sync-file-changes (pcb/empty-changes)
nil
:components
(:id updated-file)
(thi/id :component1)
(:id updated-file)
{(:id updated-file) updated-file}
(:id updated-file))
file' (thf/apply-changes updated-file changes2)
;; ==== Get
copy-child' (ths/get-shape file' :copy-child)
line (get-in copy-child' [:content :children 0 :children 0 :children 0])]
;; with no subgroup, sync takes the "nothing touched" branch and writes
;; the main's content
(tm/known-failure "F50" "copy text" "hello world" (:text line))
(t/is (= #{:content-group} (:touched copy-child')))))

View File

@ -10,6 +10,7 @@
[app.common.files.changes-builder :as pcb]
[app.common.logic.variants :as clv]
[app.common.test-helpers.components :as thc]
[app.common.test-helpers.compositions :as tho]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
@ -105,32 +106,11 @@
:first in the first column and a copy :copy01 of :c01 in the third, so the
second cell is free."
[file]
(let [file (-> file
(ths/add-sample-shape :board
:type :frame
:layout :grid
:layout-grid-dir :row
:layout-grid-rows []
:layout-grid-columns []
:layout-grid-cells {})
(ths/add-sample-shape :first :parent-label :board)
(thc/instantiate-component :c01 :copy01 :parent-label :board))
objects (:objects (thf/current-page file))
board (-> (get objects (thi/id :board))
(ctl/add-grid-row {:type :flex :value 1})
(ctl/add-grid-column {:type :flex :value 1})
(ctl/add-grid-column {:type :flex :value 1})
(ctl/add-grid-column {:type :flex :value 1}))
place (fn [cells column label]
(let [[id _] (d/seek #(= column (:column (val %))) cells)]
(assoc-in cells [id :shapes] [(thi/id label)])))
cells (-> (:layout-grid-cells board)
(place 1 :first)
(place 3 :copy01))]
(-> file
(ths/update-shape :board :layout-grid-rows (:layout-grid-rows board))
(ths/update-shape :board :layout-grid-columns (:layout-grid-columns board))
(ths/update-shape :board :layout-grid-cells cells))))
(-> file
(tho/add-grid-frame :board)
(ths/add-sample-shape :first :parent-label :board)
(thc/instantiate-component :c01 :copy01 :parent-label :board)
(tho/place-in-grid-columns :board 3 {1 :first 3 :copy01})))
(t/deftest swap-in-place-keeps-the-grid-cell
(let [file (-> (thf/sample-file :file1)

View File

@ -9,6 +9,7 @@
[app.common.files.changes-builder :as pcb]
[app.common.files.helpers :as cfh]
[app.common.geom.point :as gpt]
[app.common.geom.rect :as grc]
[app.common.geom.shapes :as gsh]
[app.common.logic.libraries :as cll]
[app.common.logic.shapes :as cls]
@ -21,6 +22,7 @@
[app.common.test-helpers.variants :as thv]
[app.common.types.component :as ctk]
[app.common.types.modifiers :as ctm]
[app.common.types.path.segment :as segment]
[clojure.set :as set]
[clojure.string :as string]
[clojure.test :as t]))
@ -47,7 +49,6 @@
file' (tho/swap-component-in-shape file :copy01 :c02 {:keep-touched? true})
copy01' (ths/get-shape file' :copy01)]
(thf/dump-file file :keys [:width])
;; The copy had width 5 before the switch
(t/is (= (:width copy01) 5))
;; The copy has width 15 after the switch
@ -112,7 +113,6 @@
file' (tho/swap-component-in-shape file :copy01 :c02 {:keep-touched? true})
copy01' (ths/get-shape file' :copy01)]
(thf/dump-file file :keys [:width])
;; The copy had width 25 before the switch
(t/is (= (:width copy01) 25))
;; The override is keept: The copy still has width 25 after the switch
@ -226,8 +226,6 @@
copy01' (ths/get-shape file' :copy01)]
(thf/dump-file file :keys [:width])
;; The copy had width 5 before the switch
(t/is (= (:width copy01) 5))
;; The copy has width 15 after the switch
@ -261,8 +259,6 @@
child01' (ths/get-shape file' :child01)]
(thf/dump-file file :keys [:width])
;; The copy had width 5 before the switch
(t/is (= (:width child01) 5))
;; The copy has width 15 after the switch
@ -309,8 +305,6 @@
copy01' (ths/get-shape file' :copy01)]
(thf/dump-file file :keys [:width :touched])
;; The copy had fill color before the switch
(t/is (= (:fills copy01) fills))
;; The copy still has fill color after the switch
@ -362,8 +356,6 @@
nested02' (ths/get-shape file' :nested02)]
(thf/dump-file file :keys [:width])
;; The copy had fill color before the switch
(t/is (= (:fills nested02) fills))
;; The copy still has fill color after the switch
@ -479,8 +471,6 @@
copy-both' (ths/get-shape file' :copy-both-2)
copy-both-t' (get-in page' [:objects (-> copy-both' :shapes first)])]
(thf/dump-file file' {:keys [:name #_:content]})
;;;;;;;;;;; Clean copy
;; Before the switch:
@ -603,8 +593,6 @@
copy-both' (ths/get-shape file' :copy-both-2)
copy-both-t' (get-in page' [:objects (-> copy-both' :shapes first)])]
(thf/dump-file file' {:keys [:name #_:content]})
;;;;;;;;;;; Clean copy
;; Before the switch:
@ -725,8 +713,6 @@
copy-both' (ths/get-shape file' :copy-both-2)
copy-both-t' (get-in page' [:objects (-> copy-both' :shapes first)])]
(thf/dump-file file' {:keys [:name #_:content]})
;;;;;;;;;;; Clean copy
;; Before the switch:
@ -849,8 +835,6 @@
copy-both' (ths/get-shape file' :copy-both-2)
copy-both-t' (get-in page' [:objects (-> copy-both' :shapes first)])]
(thf/dump-file file' {:keys [:name #_:content]})
;;;;;;;;;;; Clean copy
;; Before the switch:
@ -968,8 +952,6 @@
copy-structure-mixed' (ths/get-shape file' :copy-structure-mixed-2)
copy-structure-mixed-t' (get-in page' [:objects (-> copy-structure-mixed' :shapes first)])]
(thf/dump-file file' {:keys [:name #_:content]})
;;;;;;;;;;; Copy structure clean
;; Before the switch, first line:
;; * font size 14
@ -1099,8 +1081,6 @@
copy-structure-mixed' (ths/get-shape file' :copy-structure-mixed-2)
copy-structure-mixed-t' (get-in page' [:objects (-> copy-structure-mixed' :shapes first)])]
(thf/dump-file file' {:keys [:name #_:content]})
;;;;;;;;;;; Copy structure clean
;; Before the switch, first line:
;; * font size 14
@ -1226,8 +1206,6 @@
copy-structure-mixed' (ths/get-shape file' :copy-structure-mixed-2)
copy-structure-mixed-t' (get-in page' [:objects (-> copy-structure-mixed' :shapes first)])]
(thf/dump-file file' {:keys [:name #_:content]})
;;;;;;;;;;; Copy structure clean
;; Before the switch, first line:
;; * font size 14
@ -1354,8 +1332,6 @@
copy-structure-mixed' (ths/get-shape file' :copy-structure-mixed-2)
copy-structure-mixed-t' (get-in page' [:objects (-> copy-structure-mixed' :shapes first)])]
(thf/dump-file file' {:keys [:name #_:content]})
;;;;;;;;;;; Copy structure clean
;; Before the switch, first line:
;; * font size 14
@ -1498,7 +1474,6 @@
copy02' (ths/get-shape file' :copy02)
copy-cp02' (ths/get-shape file' :copy-cp02)]
(thf/dump-file file')
;;copy-cp02 is a copy of external02
(t/is (= (:component-id copy-cp02) (:id external02)))
;;copy-01 had copy-cp02 as child
@ -1547,7 +1522,6 @@
copy02' (ths/get-shape file' :copy02)
copy-cp02' (ths/get-shape file' :copy-cp02)
copy-cp02-rect' (ths/get-shape-by-id file' (-> copy-cp02' :shapes first))]
(thf/dump-file file')
;;copy-cp02 is a copy of external02
(t/is (= (:component-id copy-cp02) (:id external02)))
;;copy-01 had copy-cp02 as child
@ -1615,7 +1589,6 @@
c02-in-copy' (ths/get-shape file' :c02-in-copy)
rect02' (get-in page' [:objects (-> c02-in-copy' :shapes first)])]
(thf/dump-file file :keys [:width :touched])
;; The rect had width 25 before the switch
(t/is (= (:width rect01) 25))
;; The rect still has width 25 after the switch
@ -3523,3 +3496,128 @@
;; ==== Check
(t/is (mth/close? (* width (/ (:width copy02') root-w)) (:width icon')))))
;; ============================================================
;; GEOMETRY OVERRIDES FROM A REAL RESIZE
;; A transform updates :selrect and :points too, so the switch
;; carries them as well as :width and :height.
;; ============================================================
(defn- copy-child
[file label]
(let [page (thf/current-page file)]
(get-in page [:objects (-> (ths/get-shape file label) :shapes first)])))
(defn- resize-copy-child
"Resize the first child of the copy `label` by `sx`, `sy` from its top
left corner, as a transform does."
[file label sx sy]
(let [page (thf/current-page file)
child (copy-child file label)
origin (gpt/point (-> child :selrect :x) (-> child :selrect :y))
changes (cls/generate-update-shapes
(pcb/empty-changes nil (:id page))
#{(:id child)}
#(gsh/transform-shape % (ctm/resize-modifiers (gpt/point sx sy) origin))
(:objects page)
{})]
(thf/apply-changes file changes)))
(defn- size-is
"Assert that `shape`'s :selrect and :points both measure `width` x
`height`."
[shape width height]
(let [points (grc/points->rect (:points shape))]
(t/is (mth/close? width (-> shape :selrect :width)))
(t/is (mth/close? height (-> shape :selrect :height)))
(t/is (mth/close? width (:width points)))
(t/is (mth/close? height (:height points)))))
(t/deftest test-switch-keeps-a-resized-child-of-same-size-variants
(let [file (-> (thf/sample-file :file1)
(thv/add-variant-with-child
:v01 :c01 :m01 :c02 :m02 :r01 :r02
{:child1-params {:width 100 :height 50 :type :rect}
:child2-params {:width 100 :height 50 :type :rect}})
(thc/instantiate-component :c01 :copy01 :children-labels [:copy-r01])
(resize-copy-child :copy01 2 1))
;; the switch moves the labels, so read the copy before it
rect (copy-child file :copy01)
file' (tho/swap-component-in-shape file :copy01 :c02 {:new-shape-label :copy02 :keep-touched? true})
rect' (copy-child file' :copy02)]
(size-is rect 200 50)
;; the variants agree on the size, so the override is carried
(size-is rect' 200 50)
(t/is (contains? (:touched rect') :geometry-group))))
(t/deftest test-switch-with-h-sizing-fix-keeps-only-the-resized-height
(let [file (-> (thf/sample-file :file1)
(thv/add-variant-with-child
:v01 :c01 :m01 :c02 :m02 :r01 :r02
{:child1-params {:width 100 :height 50 :type :rect :layout-item-h-sizing :fix}
:child2-params {:width 100 :height 50 :type :rect :layout-item-h-sizing :fix}})
(thc/instantiate-component :c01 :copy01 :children-labels [:copy-r01])
(resize-copy-child :copy01 2 2))
rect (copy-child file :copy01)
file' (tho/swap-component-in-shape file :copy01 :c02 {:new-shape-label :copy02 :keep-touched? true})]
(size-is rect 200 100)
;; the fixed width comes from the new variant; the height override stays
(size-is (copy-child file' :copy02) 100 100)))
(t/deftest test-switch-keeps-a-resized-path-of-same-size-variants
(let [triangle (fn [x0 y0]
[{:command :move-to :params {:x x0 :y y0}}
{:command :line-to :params {:x (+ x0 24) :y y0}}
{:command :line-to :params {:x (+ x0 12) :y (+ y0 14)}}
{:command :close-path}])
file (-> (thf/sample-file :file1)
(thv/add-variant :v01 :c01 :m01 :c02 :m02
{:variant1-params {:width 100 :height 100}
:variant2-params {:width 100 :height 100}})
(ths/add-sample-shape :path1 :type :path :parent-label :m01
:content (triangle 0 10))
(ths/add-sample-shape :path2 :type :path :parent-label :m02
:content (triangle 0 30))
(thc/instantiate-component :c01 :copy01)
(resize-copy-child :copy01 2 2))
path (copy-child file :copy01)
file' (tho/swap-component-in-shape file :copy01 :c02 {:new-shape-label :copy02 :keep-touched? true})
path' (copy-child file' :copy02)
content (segment/content->selrect (:content path'))]
(size-is path 48 28)
;; the path keeps its size: its content is scaled like its box
(t/is (= :path (:type path')))
(size-is path' 48 28)
(t/is (mth/close? 48 (:width content)))
(t/is (mth/close? 28 (:height content)))))
(t/deftest test-switch-to-a-main-with-another-text-structure
;; The second variant's text has two lines where the first has one, so
;; the copy's text cannot keep its own structure. With uniform styles and
;; mains that agree on them, a style override is carried onto the new
;; variant's lines; when the mains disagree on the style, it is dropped.
(let [setup (fn [main-font-size]
(-> (thf/sample-file :file1)
(thv/add-variant-with-text
:v01 :c01 :m01 :c02 :m02 :t01 :t02 "hello world" "hello world")
(change-structure :t02)
(cond-> main-font-size
(-> (update-attr :t02 font-size-path-0 main-font-size)
(update-attr :t02 font-size-path-1 main-font-size)))
(thc/instantiate-component :c01 :copy01 :children-labels [:copy01-t])
(update-attr :copy01-t font-size-path-0 "25")))
switched (fn [file]
(-> (tho/swap-component-in-shape file :copy01 :c02
{:new-shape-label :copy02 :keep-touched? true})
(copy-child :copy02)))
agree (switched (setup nil))
disagree (switched (setup "50"))]
(t/is (= "new line 1" (get-in agree text-path-0)))
(t/is (= "new line 2" (get-in agree text-path-1)))
(t/is (= "25" (get-in agree font-size-path-0)))
(t/is (= "25" (get-in agree font-size-path-1)))
(t/is (= "new line 1" (get-in disagree text-path-0)))
(t/is (= "new line 2" (get-in disagree text-path-1)))
(t/is (= "50" (get-in disagree font-size-path-0)))
(t/is (= "50" (get-in disagree font-size-path-1)))))

View File

@ -28,6 +28,7 @@
[common-tests.files.comp-processors-test]
[common-tests.files.helpers-test]
[common-tests.files.page-diff-test]
[common-tests.files.repair-components-test]
[common-tests.files.repair-test]
[common-tests.files.shapes-builder-test]
[common-tests.files.tokens-test]
@ -73,6 +74,7 @@
[common-tests.logic.composable-sync-test]
[common-tests.logic.copying-and-duplicating-test]
[common-tests.logic.duplicated-pages-test]
[common-tests.logic.library-asset-sync-test]
[common-tests.logic.move-shapes-test]
[common-tests.logic.multiple-nesting-levels-test]
[common-tests.logic.swap-and-reset-test]
@ -105,6 +107,7 @@
[common-tests.types.color-test]
[common-tests.types.components-test]
[common-tests.types.container-test]
[common-tests.types.file-test]
[common-tests.types.fill-test]
[common-tests.types.font-test]
[common-tests.types.modifiers-test]
@ -145,6 +148,7 @@
'common-tests.files.comp-processors-test
'common-tests.files.helpers-test
'common-tests.files.page-diff-test
'common-tests.files.repair-components-test
'common-tests.files.repair-test
'common-tests.files.shapes-builder-test
'common-tests.files.tokens-test
@ -190,6 +194,7 @@
'common-tests.logic.composable-sync-test
'common-tests.logic.copying-and-duplicating-test
'common-tests.logic.duplicated-pages-test
'common-tests.logic.library-asset-sync-test
'common-tests.logic.move-shapes-test
'common-tests.logic.multiple-nesting-levels-test
'common-tests.logic.swap-and-reset-test
@ -201,8 +206,8 @@
'common-tests.logic.token-apply-test
'common-tests.logic.token-test
'common-tests.logic.variants-reparent-test
'common-tests.logic.variants-switch-test
'common-tests.logic.variants-switch-target-test
'common-tests.logic.variants-switch-test
'common-tests.logic.variants-test
'common-tests.math-test
'common-tests.media-test
@ -222,6 +227,7 @@
'common-tests.types.color-test
'common-tests.types.components-test
'common-tests.types.container-test
'common-tests.types.file-test
'common-tests.types.fill-test
'common-tests.types.font-test
'common-tests.types.modifiers-test

View File

@ -367,7 +367,6 @@
near-copy2-nested4-head (ctf/find-near-match file page-file libraries copy2-nested4-head)
near-copy2-nested4-child (ctf/find-near-match file page-file libraries copy2-nested4-child)]
(thf/dump-file library1 :keys [:name :swap-slot-label] :show-refs? true)
(t/is (some? main1-root))
(t/is (some? main1-child))
(t/is (some? main2-root))

View File

@ -6,11 +6,22 @@
(ns common-tests.types.container-test
(:require
[app.common.geom.point :as gpt]
[app.common.test-helpers.components :as thc]
[app.common.test-helpers.compositions :as tho]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[app.common.test-helpers.variants :as thv]
[app.common.types.component :as ctk]
[app.common.types.components-list :as ctkl]
[app.common.types.container :as ctc]
[app.common.types.shape :as cts]
[app.common.uuid :as uuid]
[clojure.test :as t]))
(t/use-fixtures :each thi/test-fixture)
;; ---------------------------------------------------------------------------
;; Helpers
;; ---------------------------------------------------------------------------
@ -291,3 +302,208 @@
(t/testing "two ordinary outside shapes are both kept"
(t/is (= [outside-id outside-2-id]
(vec (ctc/ids-for-structure-op objects [outside-id outside-2-id])))))))
;; ---------------------------------------------------------------------------
;; Placement rules: where shapes may go when moved or pasted
;; ---------------------------------------------------------------------------
(defn- placement-file
"A board with a frame, a group and a rect inside; components :c1 and :c2,
a copy of :c1; and two variant containers, :v01 with mains :vm1 and :vm2,
:v02 with mains :vm3 and :vm4."
[]
(-> (thf/sample-file :file)
(tho/add-frame :board)
(tho/add-frame :inner :parent-label :board)
(tho/add-group :group :parent-label :board)
(tho/add-rect :rect :parent-label :board)
(tho/add-simple-component :c1 :main1 :main1-child)
(tho/add-simple-component :c2 :main2 :main2-child)
(thc/instantiate-component :c1 :copy1 :children-labels [:copy1-child])
(thv/add-variant :v01 :vc1 :vm1 :vc2 :vm2)
(thv/add-variant :v02 :vc3 :vm3 :vc4 :vm4)))
(defn- page-objects
[file]
(:objects (thf/current-page file)))
(defn- label
[id]
(if (= id uuid/zero) :root (thi/label id)))
(defn- place
"The labels of the parent and the frame that the shapes `labels` go to
when moved, or pasted with `pasting?`, into `target`."
[file target labels & {:keys [pasting? libraries objects]}]
(let [objects (or objects (page-objects file))
children (map #(ths/get-shape file %) labels)]
(mapv label (ctc/find-valid-parent-and-frame-ids
(thi/id target) objects children pasting?
(or libraries {(:id file) file})))))
(defn- delete-component
[file component-label]
(assoc-in file [:data :components (thi/id component-label) :deleted] true))
(t/deftest placement-of-plain-shapes
(let [file (placement-file)]
(t/is (= [:board :board] (place file :board [:main1])))
(t/testing "inside a group the frame is the group's frame"
(t/is (= [:group :board] (place file :group [:rect]))))
(t/testing "the three-argument arity moves, without libraries"
(t/is (= [:inner :inner]
(mapv label (ctc/find-valid-parent-and-frame-ids
(thi/id :inner) (page-objects file)
[(ths/get-shape file :rect)])))))))
(t/deftest placement-inside-a-copy
(let [file (placement-file)]
(t/testing "nothing goes into a copy or a shape inside it"
(t/is (= [:root :root] (place file :copy1 [:rect])))
(t/is (= [:root :root] (place file :copy1-child [:rect]))))
(t/testing "a shape may stay in the copy it already is in"
(t/is (= [:copy1 :copy1] (place file :copy1 [:copy1-child]))))
(t/testing "but a pasted one is a new shape"
(t/is (= [:root :root] (place file :copy1 [:copy1-child] :pasting? true))))))
(t/deftest placement-of-a-main
(let [file (placement-file)]
(t/testing "a main is not moved into another main, nor inside one"
(t/is (= [:root :root] (place file :main2 [:main1])))
(t/is (= [:root :root] (place file :main2-child [:main1]))))
(t/testing "a plain shape may go into a main"
(t/is (= [:main2 :main2] (place file :main2 [:rect]))))
(t/testing "a pasted main becomes a copy, so it may go into a main"
(t/is (= [:main2 :main2] (place file :main2 [:main1] :pasting? true))))
(t/testing "unless its component is deleted: then it is pasted as a main"
(let [libraries {(:id file) (delete-component file :c1)}]
(t/is (= [:root :root] (place file :main2 [:main1] :pasting? true :libraries libraries)))))
(t/testing "a cut main, no longer in the page, follows the same rule"
(let [objects (dissoc (page-objects file) (thi/id :main1) (thi/id :main1-child))
libraries {(:id file) (delete-component file :c1)}]
(t/is (= [:main2 :main2] (place file :main2 [:main1] :pasting? true :objects objects)))
(t/is (= [:root :root] (place file :main2 [:main1] :pasting? true
:objects objects :libraries libraries)))))))
(t/deftest placement-of-a-variant-container
(let [file (placement-file)]
(t/is (= [:board :board] (place file :board [:v01])))
(t/testing "not inside another variant container"
(t/is (= [:root :root] (place file :v02 [:v01]))))
(t/testing "not inside a main, even pasted"
(t/is (= [:root :root] (place file :main2 [:v01] :pasting? true))))))
(t/deftest placement-inside-a-variant-container
(let [file (placement-file)]
(t/testing "only mains go into a variant container"
(t/is (= [:root :root] (place file :v01 [:rect])))
(t/is (= [:v01 :v01] (place file :v01 [:main1]))))
(t/testing "a pasted variant does not go inside a sibling variant"
(t/is (= [:v01 :v01] (place file :vm2 [:vm1] :pasting? true))))
(t/testing "but it may go inside a variant of another container"
(t/is (= [:vm3 :vm3] (place file :vm3 [:vm1] :pasting? true))))))
(t/deftest placement-that-makes-a-component-loop
(let [file (placement-file)]
(t/testing "a copy does not go inside its own main"
(t/is (= [:root :root] (place file :main1 [:copy1] :pasting? true)))
(t/is (= [:main2 :main2] (place file :main2 [:copy1] :pasting? true))))
(t/testing "a main does not go inside itself, even pasted"
(t/is (= [:root :root] (place file :main1-child [:main1])))
(t/is (= [:root :root] (place file :main1-child [:main1] :pasting? true))))
(t/testing "a plain shape inside its own child is let through (`relocate-shapes` drops it)"
(t/is (= [:inner :inner] (place file :inner [:board]))))))
(t/deftest placement-with-a-validation-cache
(let [file (placement-file)
objects (page-objects file)
children [(ths/get-shape file :main1)]
libs {(:id file) file}
cache (ctc/parent-validation-cache objects children libs)]
(t/is (= [:root :root]
(mapv label (ctc/find-valid-parent-and-frame-ids
(thi/id :main2) objects children false libs cache))))
(t/is (= [:board :board]
(mapv label (ctc/find-valid-parent-and-frame-ids
(thi/id :board) objects children false libs cache))))))
(t/deftest valid-shape-for-component
(let [file (placement-file)
objects (page-objects file)
valid? #(ctc/valid-shape-for-component? objects (ths/get-shape file %))]
(t/is (valid? :rect))
(t/is (valid? :board))
(t/testing "a main can't be inside another main"
(t/is (not (valid? :main1-child))))
(t/testing "a main can't hold another main"
(t/is (not (valid? :v01))))
(t/testing "a main can't be inside a copy"
(t/is (not (valid? :copy1-child))))))
(t/deftest first-valid-parent
(let [file (placement-file)
objects (page-objects file)
first-valid #(label (:id (ctc/get-first-valid-parent objects (thi/id %))))]
(t/is (= :rect (first-valid :rect)))
(t/is (= :vm1 (first-valid :vm1)))
(t/testing "copies and variant containers are skipped"
(t/is (= :root (first-valid :copy1-child)))
(t/is (= :root (first-valid :v01))))))
;; ---------------------------------------------------------------------------
;; Heads, containers and instances
;; ---------------------------------------------------------------------------
(t/deftest head-shape-of-nothing-and-of-the-root
(let [objects (page-objects (placement-file))]
(t/is (nil? (ctc/get-head-shape objects nil)))
(t/is (nil? (ctc/get-head-shape objects (get objects uuid/zero))))
(t/is (= [] (ctc/get-child-heads objects (uuid/next))))))
(t/deftest children-in-instance-stop-at-a-nested-copy
(let [file (-> (thf/sample-file :file)
(tho/add-nested-component :c1 :main1 :main1-child
:c2 :main2 :nested-head))
objects (page-objects file)
labels #(set (map (comp label :id) (ctc/get-children-in-instance objects (thi/id %))))]
(t/is (= #{:main1 :main1-child} (labels :main1)))
(t/is (= #{:main2} (labels :main2)))))
(t/deftest container-of-a-component
(let [file (placement-file)
container (ctc/get-container (:data file) :component (thi/id :c1))]
(t/is (ctc/component? container))
(t/is (not (ctc/page? container)))
(t/is (= (thi/id :main1) (:main-instance-id container)))))
(t/deftest container-root
(let [root-id (uuid/next)
root (assoc (make-shape root-id) :parent-id nil)
child (make-shape (uuid/next) :parent-id root-id)]
(t/is (= root (ctc/get-container-root {:objects (objects-map root child)})))))
(t/deftest swap-keep-attrs-keep-auto-sizing-of-a-layout
(let [shape (make-shape (uuid/next)
:type :frame
:layout :flex
:layout-item-h-sizing :auto
:layout-item-v-sizing :auto
:layout-item-margin {:m1 10})
fixed (assoc shape
:layout-item-h-sizing :fix
:layout-item-v-sizing :fix)]
(t/is (= [:auto :auto nil]
((juxt :layout-item-h-sizing :layout-item-v-sizing :layout-item-margin)
(ctc/remove-swap-keep-attrs shape))))
(t/is (= [nil nil]
((juxt :layout-item-h-sizing :layout-item-v-sizing)
(ctc/remove-swap-keep-attrs fixed))))))
(t/deftest component-instance-with-default-options
(let [file (placement-file)
component (ctkl/get-component (:data file) (thi/id :c1))
[root shapes] (ctc/make-component-instance (thf/current-page file) component
(:data file) (gpt/point 0 0))]
(t/is (= (thi/id :c1) (:component-id root)))
(t/is (not (ctk/main-instance? root)))
(t/is (= 2 (count shapes)))))

View File

@ -0,0 +1,293 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns common-tests.types.file-test
"Component helpers of `app.common.types.file`: the export detach of
external references, the library page that absorbed components go to,
the original ref of a swapped shape, and the lookups on deleted
components."
(:require
[app.common.files.validate :as cfv]
[app.common.test-helpers.components :as thc]
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.compositions :as tho]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[app.common.types.component :as ctk]
[app.common.types.container :as ctn]
[app.common.types.file :as ctf]
[app.common.types.pages-list :as ctpl]
[app.common.types.shape-tree :as ctst]
[clojure.test :as t]))
(t/use-fixtures :each thi/test-fixture)
(def ^:private link-attrs
[:component-id :component-file :shape-ref :component-root])
(defn- links
[file label]
(select-keys (ths/get-shape file label) link-attrs))
(defn- validation-errors
[file]
(set (map :code (cfv/validate-file file {}))))
(defn- library-with-component
[]
(-> (thf/sample-file :library :is-shared true)
(tho/add-simple-component :lib-component :lib-main :lib-main-child)))
;; ----- Export detach
(t/deftest detach-external-references-drops-library-links
(let [library (library-with-component)
file (-> (thf/sample-file :file)
(tho/add-simple-component-with-copy :component :main :main-child
:copy
:copy-root-params {:children-labels [:copy-child]})
(thc/instantiate-component :lib-component :lib-copy
:library library
:children-labels [:lib-copy-child]))
file' (ctf/detach-external-references file (:id file))]
(t/testing "a copy of a library component becomes plain shapes"
(t/is (= {} (links file' :lib-copy)))
(t/is (= {} (links file' :lib-copy-child))))
(t/testing "a copy of a local component keeps its links"
(t/is (= (links file :copy) (links file' :copy)))
(t/is (= (links file :copy-child) (links file' :copy-child))))
(t/is (= #{} (validation-errors file')))))
(t/deftest detach-external-references-keeps-a-nested-library-copy-in-place
(let [library (library-with-component)
file (-> (thf/sample-file :file)
(tho/add-frame :main {:name "Frame2"})
(thc/instantiate-component :lib-component :nested-head
:library library
:parent-label :main)
(thc/make-component :component :main)
(thc/instantiate-component :component :copy
:children-labels [:copy-nested-head]))
file' (ctf/detach-external-references file (:id file))]
(t/testing "the nested library copy in the main becomes plain shapes"
(t/is (= {} (links file' :nested-head))))
(t/testing "its copy keeps the ref to the main's shape, which is local"
(tm/known-failure "F52"
{:shape-ref (thi/id :nested-head)}
{}
(links file' :copy-nested-head)))
(t/testing "the validation does not see the lost ref"
(t/is (= #{} (validation-errors file'))))))
;; Fill and typography refs on the shape and on the text nodes themselves
;; (the older format), next to a fill ref inside `:fills`.
(defn- file-with-color-refs
[library-id]
(let [file (thf/sample-file :file)]
(-> file
(ths/add-sample-shape :rect
:type :rect
:fill-color-ref-id (thi/id :color)
:fill-color-ref-file library-id
:stroke-color-ref-id (thi/id :color)
:stroke-color-ref-file library-id
:fills [{:fill-color "#abcdef"
:fill-opacity 1
:fill-color-ref-id (thi/id :color)
:fill-color-ref-file library-id}])
(ths/add-sample-shape :text
:type :text
:content {:type "root"
:children [{:type "paragraph-set"
:children [{:type "paragraph"
:children [{:text "library"
:fill-color-ref-id (thi/id :color)
:fill-color-ref-file library-id
:typography-ref-id (thi/id :typography)
:typography-ref-file library-id}
{:text "local"
:typography-ref-id (thi/id :typography)
:typography-ref-file (:id file)}]}]}]}))))
(defn- text-leaves
[file]
(->> (get-in (ths/get-shape file :text) [:content :children 0 :children 0 :children])
(mapv #(select-keys % [:fill-color-ref-file :typography-ref-file]))))
(t/deftest detach-external-references-drops-library-color-refs
(let [library-id (thi/new-id! :library)
file (file-with-color-refs library-id)
file' (ctf/detach-external-references file (:id file))
rect' (ths/get-shape file' :rect)]
(t/is (= {} (select-keys rect' [:fill-color-ref-file :stroke-color-ref-file])))
(t/is (= [{} {:typography-ref-file (:id file)}] (text-leaves file')))
(t/testing "a fill ref inside `:fills`"
(tm/known-failure "F57" nil library-id (-> rect' :fills first :fill-color-ref-file)))))
;; ----- Asset usage
(t/deftest component-used-in-a-file
(let [library (library-with-component)
file (-> (thf/sample-file :file)
(thc/instantiate-component :lib-component :lib-copy :library library))
unused (-> (thf/sample-file :other)
(tho/add-rect :rect))
lib-c (thc/get-component library :lib-component)]
(t/is (ctf/used-in? (:data file) (:id library) lib-c :component))
(t/is (not (ctf/used-in? (:data unused) (:id library) lib-c :component)))))
;; ----- Library page for absorbed components
(t/deftest absorbed-components-reuse-the-library-page
(let [library1 (-> (thf/sample-file :library1 :is-shared true)
(tho/add-simple-component :component1 :main1 :main1-child))
library2 (-> (thf/sample-file :library2 :is-shared true)
(tho/add-simple-component :component2 :main2 :main2-child))
file (-> (thf/sample-file :file)
(thc/instantiate-component :component1 :copy1 :library library1)
(thc/instantiate-component :component2 :copy2 :library library2))
file' (ctf/update-file-data file
#(-> %
(ctf/absorb-assets (:data library1))
(ctf/absorb-assets (:data library2))))
data' (ctf/file-data file')
pages' (ctpl/pages-seq data')
roots (->> (ctpl/get-page data' (:id (second pages')))
(ctn/shapes-seq)
(filter ctk/main-instance?)
(sort-by :y))]
(t/is (= ["Page 1" "Main components"] (map :name pages')))
(t/is (= 2 (count roots)))
(t/testing "the second component goes below the first, a grid gap apart"
(let [[first-root second-root] roots]
(t/is (<= (+ (:y first-root) (:height first-root) 50) (:y second-root)))))
(t/is (= #{} (validation-errors file')))))
;; ----- Original ref of a swapped shape
(defn- swap-at-second-level
"Swaps, in a copy of :c3, the copy of :c1 nested two levels down
(:c3 > :c2 > :c1) for :c4. Returns the file with the new shape as
:swapped."
[file]
(let [copy-c2 (first (:shapes (ths/get-shape file :copy3)))
copy-c1 (first (:shapes (ths/get-shape-by-id file copy-c2)))]
(thi/set-id! :copy-c1 copy-c1)
(-> file
(tho/add-simple-component :c4 :main4 :main4-child)
(tho/swap-component-in-shape :copy-c1 :c4 :new-shape-label :swapped))))
(defn- ref-id-for-swapped
[file]
(ctf/find-ref-id-for-swapped (ths/get-shape file :swapped)
(thf/current-page file)
{(:id file) file}))
(t/deftest ref-id-for-swapped-goes-up-the-ref-chain
(let [file (-> (thf/sample-file :file)
(tho/add-two-levels-nested-component-with-copy
:c1 :main1 :main1-child
:c2 :main2 :nested-head1
:c3 :main3 :nested-head2 :nested-subhead2
:copy3)
(swap-at-second-level))]
(t/is (= (thi/id :nested-head1) (ctk/get-swap-slot (ths/get-shape file :swapped))))
(t/is (= (thi/id :nested-subhead2) (ref-id-for-swapped file)))))
(t/deftest ref-id-for-swapped-with-mains-on-other-pages
(let [file (-> (thf/sample-file :file :page-label :page1)
(tho/add-nested-component :c1 :main1 :main1-child
:c2 :main2 :nested-head1)
(thf/add-sample-page :page2)
(tho/add-frame :main3 {:name "Frame3"})
(thc/instantiate-component :c2 :nested-head2
:parent-label :main3
:children-labels [:nested-subhead2])
(thc/make-component :c3 :main3)
(thc/instantiate-component :c3 :copy3)
(swap-at-second-level))]
(t/is (= (thi/id :nested-head1) (ctk/get-swap-slot (ths/get-shape file :swapped))))
(tm/known-failure "F56" (thi/id :nested-subhead2) nil (ref-id-for-swapped file))))
;; ----- Deleted components
(defn- file-with-deleted-component
[]
(let [file (-> (thf/sample-file :file)
(tho/add-simple-component :component :main :main-child))]
(ctf/update-file-data file #(ctf/delete-component % (thi/id :component) false nil))))
(t/deftest lookups-on-a-deleted-component
(let [file (file-with-deleted-component)
data (ctf/file-data file)
component (thc/get-component file :component :include-deleted? true)]
(t/is (:deleted component))
(t/is (= (thi/id :main) (:id (ctf/get-component-root data component))))
(t/is (= #{(thi/id :main) (thi/id :main-child)}
(set (map :id (ctf/get-component-shapes data component)))))
(t/testing "a shape of the component, with the component as its container"
(let [child (ctf/get-component-shape data component (thi/id :main-child)
:with-context? true)]
(t/is (= (thi/id :main-child) (:id child)))
(t/is (= :component (:type (:container (meta child)))))))
(t/testing "loading the objects again leaves the component as it is"
(t/is (= component (ctf/load-component-objects data component))))))
;; ----- Containers and ref chains
(t/deftest update-container-of-a-component
(let [file (file-with-deleted-component)
component (thc/get-component file :component :include-deleted? true)
container (ctn/make-container component :component)
data' (ctf/update-container (ctf/file-data file) container
#(assoc % :name "Renamed"))]
(t/is (= "Renamed" (:name (thc/get-component {:data data'} :component
:include-deleted? true))))))
(t/deftest update-objects-tree-updates-and-removes
(let [file (-> (thf/sample-file :file)
(tho/add-frame-with-child :frame :child)
(tho/add-rect :rect))
container (ctn/make-container (thf/current-page file) :page)
result (ctf/update-objects-tree
container
(fn [shape]
(condp = (:id shape)
(thi/id :frame) {:result :update
:updated-shape (assoc shape :name "Updated")}
(thi/id :rect) {:result :remove}
{:result :keep})))]
(t/is (= "Updated" (:name (ctst/get-shape result (thi/id :frame)))))
(t/is (some? (ctst/get-shape result (thi/id :child))))
(t/is (nil? (ctst/get-shape result (thi/id :rect))))
(t/testing "an unknown result"
(t/is (thrown? #?(:clj Exception :cljs :default)
(ctf/update-objects-tree container (constantly {:result :other})))))))
(t/deftest ref-chain-without-the-target
(let [file (-> (thf/sample-file :file)
(tho/add-simple-component-with-copy :component :main :main-child
:copy
:copy-root-params {:children-labels [:copy-child]}))
page (thf/current-page file)
libraries {(:id file) file}
chain (ctf/get-ref-chain-until-target-ref page libraries
(ths/get-shape file :copy-child)
(ths/get-shape file :copy))]
(t/testing "the chain runs to the main and stops there"
(t/is (= [(thi/id :copy-child) (thi/id :main-child)] (map :id chain))))))
(t/deftest near-match-with-context
(let [file (-> (thf/sample-file :file)
(tho/add-simple-component-with-copy :component :main :main-child
:copy
:copy-root-params {:children-labels [:copy-child]}))
match (ctf/find-near-match file (thf/current-page file) {(:id file) file}
(ths/get-shape file :copy-child)
:with-context? true)]
(t/is (= (thi/id :main-child) (:id match)))
(t/is (some? (:container (meta match))))))

View File

@ -6,26 +6,14 @@
(ns frontend-tests.composable-tests.comp.sync-test
"Runs the shared composable component cases
(`app.common.test-helpers.composable.comp.cases`) against the REAL app
(frontend interpreter). In-file propagation is AUTOMATIC: a case contains
ONLY the user edit(s) (no propagate op); the app's component-change watcher
syncs copies on its own, and that is what the cases assert.
Async: each deftest uses `t/async`; `ftm/check` drives the store and calls
`done` when finished."
(`app.common.test-helpers.composable.comp.cases`) through the frontend
interpreter, where the app's component watcher syncs the copies."
(:require
[app.common.test-helpers.composable.comp.cases :as cases]
[cljs.test :as t :include-macros true]
[frontend-tests.composable-tests.interpreter :as ftm]))
;; Disable thumbnail rendering for the duration of each (async) test: the
;; propagation watcher schedules thumbnail renders that reach `window`, absent in
;; the headless runner. `:each` `:after` runs only after the test's `done` fires
;; (same guarantee the wasm-mock fixtures rely on), so the no-op covers the whole
;; async lifetime and is scoped to THIS namespace. See ftm/install-thumbnail-noop!.
(t/use-fixtures :each
{:before ftm/install-thumbnail-noop!
:after ftm/restore-thumbnail!})
(t/use-fixtures :each ftm/fixture)
(t/deftest case-b-copy-override-survives-later-main-change
(t/async done (ftm/check done (cases/copy-override-survives-later-main-change))))
@ -45,6 +33,9 @@
(t/deftest case-i-undo-reverts-edit-and-its-auto-propagation
(t/async done (ftm/check done (cases/undo-reverts-edit-and-its-propagation))))
(t/deftest case-p-redo-reapplies-edit-and-its-auto-propagation
(t/async done (ftm/check done (cases/redo-reapplies-edit-and-its-propagation))))
(t/deftest case-h-library-change-propagates-across-file-boundary-on-sync
(t/async done (ftm/check done (cases/library-change-propagates-across-file-boundary-on-sync))))
@ -60,8 +51,116 @@
(t/deftest case-o-variant-switch-keeps-override-only-where-mains-agree
(t/async done (ftm/check done (cases/variant-switch-keeps-override-only-where-mains-agree))))
(t/deftest case-q-detach-keeps-nested-copies-linked
(t/async done (ftm/check done (cases/detach-keeps-nested-copies-linked))))
(t/deftest case-r-update-main-reaches-other-copies
(t/async done (ftm/check done (cases/update-main-reaches-other-copies))))
(t/deftest case-s-deleted-component-copies-sync-again-after-restore
(t/async done (ftm/check done (cases/deleted-component-copies-sync-again-after-restore))))
(t/deftest case-t-duplicated-copy-keeps-overrides-and-link
(t/async done (ftm/check done (cases/duplicated-copy-keeps-overrides-and-link))))
(t/deftest case-u-nested-copy-reaches-copies-of-the-receiving-main
(t/async done (ftm/check done (cases/nested-copy-reaches-copies-of-the-receiving-main))))
(t/deftest case-v-new-edit-after-undo-clears-redo
(t/async done (ftm/check done (cases/new-edit-after-undo-clears-redo))))
(t/deftest case-w-undo-several-steps-over-nested-cascades
(t/async done (ftm/check done (cases/undo-several-steps-over-nested-cascades))))
(t/deftest case-x-undo-before-sync-leaves-copies-unchanged
(t/async done (ftm/check done (cases/undo-before-sync-leaves-copies-unchanged))))
(t/deftest case-aj-reflow-after-nested-sync-is-its-own-undo-step
(t/async done (ftm/check done (cases/reflow-after-nested-sync-is-its-own-undo-step))))
(t/deftest case-y-text-override-merges-with-main-text-change
(t/async done (ftm/check done (cases/text-override-merges-with-main-text-change))))
(t/deftest case-n-geometry-sync-with-rotated-instances
(t/async done (ftm/check done (cases/geometry-sync-with-rotated-instances))))
(t/deftest case-touched-copy-child-survives-main-rotation
(t/async done (ftm/check done (cases/touched-copy-child-survives-main-rotation))))
(t/deftest case-z-main-child-move-reaches-copies
(t/async done (ftm/check done (cases/main-child-move-reaches-copies))))
(t/deftest case-aa-copy-swap-survives-main-changes
(t/async done (ftm/check done (cases/copy-swap-survives-main-changes))))
(t/deftest case-ab-reset-of-nested-swap-keeps-top-copy-overrides
(t/async done (ftm/check done (cases/reset-of-nested-swap-keeps-top-copy-overrides))))
(t/deftest case-ac-second-variant-switch-keeps-root-overrides
(t/async done (ftm/check done (cases/second-variant-switch-keeps-root-overrides))))
(t/deftest case-ad-update-main-pushes-a-swapped-child
(t/async done (ftm/check done (cases/update-main-pushes-a-swapped-child))))
(t/deftest case-ae-detached-or-duplicated-swapped-copy-follows-its-component
(t/async done (ftm/check done (cases/detached-or-duplicated-swapped-copy-follows-its-component))))
(t/deftest case-af-grid-cell-move-reaches-a-swapped-copy-child
(t/async done (ftm/check done (cases/grid-cell-move-reaches-a-swapped-copy-child))))
(t/deftest case-ag-main-reorder-keeps-copy-sub-heads-aligned
(t/async done (ftm/check done (cases/main-reorder-keeps-copy-sub-heads-aligned))))
(t/deftest case-ah-copy-sub-head-delete-keeps-others-aligned
(t/async done (ftm/check done (cases/copy-sub-head-delete-keeps-others-aligned))))
(t/deftest case-ai-copy-sub-head-delete-and-reflow-keeps-others-aligned
(t/async done (ftm/check done (cases/copy-sub-head-delete-and-reflow-keeps-others-aligned))))
(t/deftest case-ak-update-main-pushes-grid-cells
(t/async done (ftm/check done (cases/update-main-pushes-grid-cells))))
(t/deftest case-al-update-main-renames-the-component
(t/async done (ftm/check done (cases/update-main-renames-the-component))))
(t/deftest case-am-update-main-pushes-a-swap-inside-a-group
(t/async done (ftm/check done (cases/update-main-pushes-a-swap-inside-a-group))))
(t/deftest case-an-flex-child-override-follows-sync-reset-and-update-main
(t/async done (ftm/check done (cases/flex-child-override-follows-sync-reset-and-update-main))))
(t/deftest case-ao-copy-dropped-into-a-grid-cell-reaches-copies
(t/async done (ftm/check done (cases/copy-dropped-into-a-grid-cell-reaches-copies))))
(t/deftest case-ap-library-main-child-removal-reaches-copy
(t/async done (ftm/check done (cases/library-main-child-removal-reaches-copy))))
(t/deftest case-aq-main-change-reaches-a-copy-nested-in-a-sub-board
(t/async done (ftm/check done (cases/main-change-reaches-a-copy-nested-in-a-sub-board))))
(t/deftest case-ar-variant-property-edits-keep-copies
(t/async done (ftm/check done (cases/variant-property-edits-keep-copies))))
(t/deftest case-as-added-variant-is-a-switch-target
(t/async done (ftm/check done (cases/added-variant-is-a-switch-target))))
(t/deftest case-at-transformed-component-keeps-its-copies
(t/async done (ftm/check done (cases/transformed-component-keeps-its-copies))))
(t/deftest case-au-combined-components-keep-their-copies
(t/async done (ftm/check done (cases/combined-components-keep-their-copies))))
(t/deftest case-av-variant-rename-reaches-copy-names
(t/async done (ftm/check done (cases/variant-rename-reaches-copy-names))))
(t/deftest case-aw-variant-layer-rename-and-cleanup
(t/async done (ftm/check done (cases/variant-layer-rename-and-cleanup))))
(t/deftest case-ax-variant-shortcuts-add-members
(t/async done (ftm/check done (cases/variant-shortcuts-add-members))))
(t/deftest case-ay-token-on-a-main-reaches-copies
(t/async done (ftm/check done (cases/token-on-a-main-reaches-copies))))
(t/deftest case-az-copy-moved-out-of-its-main-keeps-inherited-overrides
(t/async done (ftm/check done (cases/copy-moved-out-of-its-main-keeps-inherited-overrides))))

View File

@ -0,0 +1,160 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.composable-tests.completion-contract-test
"Tests the interpreter's completion contract: a step resolves only once the
work it caused has drained, whatever kind of commit it makes, and reports
the pending work when it does not drain in time. Component sync is slowed
down on purpose, so a step that resolved early would see a half-synced
file."
(:require
[app.common.test-helpers.composable.comp.nodes :as n]
[app.common.test-helpers.composable.comp.setups :as setup]
[app.common.test-helpers.composable.comp.undo-check :as uc]
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[app.main.data.workspace.libraries :as dwl]
[app.main.data.workspace.reflow :as wrf]
[app.main.data.workspace.shapes :as dwsh]
[app.main.data.workspace.undo :as dwu]
[app.main.store :as st]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
[frontend-tests.composable-tests.interpreter :as ftm]
[frontend-tests.helpers.mock :as mock]
[potok.v2.core :as ptk]))
(t/use-fixtures :each ftm/fixture)
(def ^:private original "#abcdef")
(def ^:private red "#ff0000")
;; How much later than asked the slowed-down sync starts.
(def ^:private sync-delay-ms 150)
(defn- deferred-sync-file
"A replacement for `dwl/sync-file` that holds its sync wait open and runs
`work` on the event that `sync-file`, the real constructor, builds."
[sync-file work]
(mock/stub
(fn [& args]
(let [event (apply sync-file args)
file-id (first args)]
(ptk/reify ::deferred-sync-file
ptk/WatchEvent
(watch [_ _ _]
(wrf/with-pending :sync-file [file-id] (work event))))))))
(defn- slow-sync
[event]
(->> (rx/of event)
(rx/delay sync-delay-ms)))
(defn- endless-sync
[_]
(rx/create (fn [_] nil)))
(defn- fill-main-child
[color]
(dwsh/update-shapes #{(thi/id :main-child)}
#(assoc % :fills (ths/sample-fills-color :fill-color color))))
(t/deftest ^:async edit-step-waits-for-slow-sync
(let [sync-file dwl/sync-file]
(await
(mock/with-mocks*
{dwl/sync-file (deferred-sync-file sync-file slow-sync)}
(ftm/install! (setup/simple-component-with-labeled-copy))
(t/is (= :settled (await (ftm/await-step [(fill-main-child red)]))))
(t/is (= red (ftm/fill-of :copy-child)))))))
(t/deftest ^:async undo-and-redo-steps-follow-a-slow-sync
;; Undo must find the slow sync already committed: it reverts the edit and
;; its sync together only when both are on the undo stack.
(let [sync-file dwl/sync-file]
(await
(mock/with-mocks*
{dwl/sync-file (deferred-sync-file sync-file slow-sync)}
(ftm/install! (setup/simple-component-with-labeled-copy))
(await (ftm/await-step [(fill-main-child red)]))
(t/is (= red (ftm/fill-of :copy-child)) "the edit step ends synced")
(t/is (= :settled (await (ftm/await-step [dwu/undo]))))
(t/is (= original (ftm/fill-of :main-child)))
(t/is (= original (ftm/fill-of :copy-child)))
(t/is (= :settled (await (ftm/await-step [dwu/redo]))))
(t/is (= red (ftm/fill-of :main-child)))
(t/is (= red (ftm/fill-of :copy-child)))))))
(defn- watch-touches
"Collect the ids of the components that `touch-component` events touch from
now on. Returns `[ids-atom subscription]`."
[]
(let [touched (atom #{})
sub (rx/sub! (rx/filter (ptk/type? ::dwl/touch-component) st/stream)
(fn [event] (swap! touched into @event)))]
[touched sub]))
(t/deftest ^:async undo-and-redo-steps-wait-for-the-watcher
;; Undo and redo start no sync: the watcher only touches the component, a
;; timer turn after the commit. A step that resolved on the commit alone
;; would finish before that touch.
(ftm/install! (setup/simple-component-with-labeled-copy))
(await (ftm/await-step [(fill-main-child red)]))
(let [component #{(thi/id :component1)}
[touched sub] (watch-touches)]
(t/is (= :settled (await (ftm/await-step [dwu/undo]))))
(t/is (= component @touched) "the undo step waited for the watcher")
(reset! touched #{})
(t/is (= :settled (await (ftm/await-step [dwu/redo]))))
(t/is (= component @touched) "the redo step waited for the watcher")
(rx/dispose! sub)))
(t/deftest ^:async dropped-commit-steps-settle
;; Translation and derived commits start no sync; their steps must still
;; resolve.
(ftm/install! (setup/simple-component-with-labeled-copy))
(t/is (= :settled (await (ftm/await-step [(ftm/fill-commit :main-child red {:translation? true})]))))
(t/is (= :settled (await (ftm/await-step [(ftm/fill-commit :main-child red {:skip-component-sync? true})])))))
(defn- run-endless-step
"Install a component whose sync never finishes and run a main edit step with
a short timeout. Resolves with the step result and the file id."
[]
(let [sync-file dwl/sync-file]
(mock/with-mocks*
{dwl/sync-file (deferred-sync-file sync-file endless-sync)}
(ftm/install! (setup/simple-component-with-labeled-copy))
(-> (ftm/await-step [(fill-main-child red)] 100)
(.then (fn [result] [result (:id (ftm/current-file))]))))))
(t/deftest ^:async step-that-never-settles-reports-the-pending-work
(let [[result file-id] (await (run-endless-step))]
(t/is (contains? (get-in result [:timeout file-id]) :sync-file))))
(t/deftest ^:async timed-out-step-does-not-hold-up-the-next-variant
;; The endless sync stays pending; installing the next variant forgets it.
(await (run-endless-step))
(ftm/install! (setup/simple-component-with-labeled-copy))
(t/is (empty? (wrf/pending)))
(t/is (= :settled (await (ftm/await-step [(fill-main-child red)]))))
(t/is (= red (ftm/fill-of :copy-child))))
(t/deftest skipped-optional-keeps-the-undo-baseline
;; The end-of-variant round trip undoes back to the last file install. A
;; skipped optional installs nothing, so the baseline stays at the setup,
;; before the edit, where the undo index is -1.
(t/async done
(let [later (n/change-property :copy-instance :fills red)]
(ftm/check done
{:setup setup/simple-component-with-labeled-copy
:operation (tm/in-sequence [(n/change-property :main-instance :fills red)
(tm/optional later)])}
(fn [situation]
(when-not (tm/applied? situation later)
(t/is (= -1 (:depth (uc/baseline situation))))))))))

View File

@ -5,71 +5,53 @@
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.composable-tests.interpreter
"FRONTEND interpreter + test-facing `check` for the composable test model.
The generic engine lives in `app.common.test-helpers.composable.core` and the
component instruments (operation records, setups, role accessors, inspection
methods) behind the `comp` boundary. What lives HERE is:
1. `op->events` — the event realisation of each EVENT-op: the real
workspace event(s) it dispatches (it depends on
`app.main.data.workspace.*`).
2. an ASYNC interpreter that drives a sequence of operations through the REAL
app: it installs the situation's file into the global store, starts the
real component-change watcher, then for each operation dispatches its
event(s) and AWAITS settlement (so the app's AUTOMATIC propagation — not a
manual sync — is what runs), re-reading the file from the store after each.
3. `check` — the test-facing entry: takes {:setup :operation} + an OPTIONAL
asserter; enumerates the operation and runs each variant; assertions may
be inline (`Test` ops) and/or in the asserter.
IN-FILE PROPAGATION IS AUTOMATIC: there is no propagate operation. The watcher
(`dwl/watch-component-changes`), running on the global store, detects
main-instance changes in the CURRENT file and syncs that file's copies on its
own. That automatic behaviour is precisely what the cases exercise. The one
deliberate exception is CROSS-FILE propagation (case H): when the main lives
in a linked LIBRARY and the copy in the consuming file, the watcher does NOT
cross the file boundary — the real app propagates via the library-UPDATE
action, so the `SyncFromLibrary` op explicitly dispatches `sync-file` (this is
faithful: it is exactly the user action, not a test shortcut). See
`mem:frontend/composable-component-tests`.
NOTE on the store: this uses the GLOBAL `st/state` store (not the isolated
`setup-store`), because the watcher reads `refs/workspace-data` which derives
from `st/state`. State is re-installed per variant for isolation."
"Runs composable component cases through the frontend (see
`mem:frontend/composable-component-tests`). It installs the situation's
files in the global store (the component watcher reads it through
`app.main.refs`), starts the workspace watchers, maps each user operation
to the workspace events a user action dispatches (`op->events`) and waits
for the work they cause (`await-step`). The app's own watcher syncs the
copies; only the library update of case H is an explicit `sync-file`, as
in the app. `check` is the test entry point."
(:require
[app.common.data :as d]
[app.common.files.changes-builder :as pcb]
[app.common.files.tokens :as cfo]
[app.common.logic.shapes :as cls]
[app.common.test-helpers.composable.comp.nodes :as n]
[app.common.test-helpers.composable.comp.undo-check :as uc]
[app.common.test-helpers.composable.core :as tm]
[app.common.test-helpers.files :as cthf]
[app.common.test-helpers.ids-map :as cthi]
[app.common.test-helpers.shapes :as cths]
[app.common.uuid :as uuid]
[app.main.data.changes :as dch]
[app.main.data.workspace :as dw]
[app.main.data.workspace.libraries :as dwl]
[app.main.data.workspace.reflow :as wrf]
[app.main.data.workspace.selection :as dws]
[app.main.data.workspace.shape-layout :as dwsl]
[app.main.data.workspace.shapes :as dwsh]
[app.main.data.workspace.texts :as dwtx]
[app.main.data.workspace.thumbnails :as dwth]
[app.main.data.workspace.tokens.application :as dwta]
[app.main.data.workspace.transforms :as dwt]
[app.main.data.workspace.undo :as dwu]
[app.main.data.workspace.variants :as dwv]
[app.main.features :as features]
[app.main.repo :as rp]
[app.main.store :as st]
[app.plugins.reflow :as pwrf]
[app.util.dom :as dom]
[beicon.v2.core :as rx]
[cljs.test :as t]
[frontend-tests.helpers.mock :as mock]
[frontend-tests.helpers.pages :as thp]
[potok.v2.core :as ptk]))
;; --------------------------------------------------------------------------
;; (0) Thumbnail rendering — disabled in this headless suite
;;
;; The propagation watcher we start (`dwl/watch-component-changes`) ALSO schedules
;; THUMBNAIL renders on every component change (its `component-changed` event has a
;; thumbnail branch). Thumbnail rendering reaches `app.util.dom/get-css-variable`,
;; which calls `window.getComputedStyle` — and there is no `window` in the headless
;; runner, so a (queued, async) render fires LATER and crashes the run. Thumbnails
;; are pure UI side-effect, irrelevant to what we test, so we stub the public seam
;; `dwth/update-thumbnail` to a no-op event for the duration of OUR tests (installed
;; / restored by a `:each` fixture in the case namespace — the same `set!`-and-
;; restore pattern as `frontend_tests.helpers.wasm`, whose `:after` correctly runs
;; only after each async test's `done`). Scope is thus our suite only.
;; Thumbnails: the component watcher renders them, which reaches `window`,
;; absent headless, so tests stub `dwth/update-thumbnail` (see `fixture`).
;; --------------------------------------------------------------------------
(defonce ^:private original-update-thumbnail (atom nil))
@ -95,142 +77,248 @@
(set! dwth/update-thumbnail orig)
(reset! original-update-thumbnail nil)))
(def fixture
"An `:each` fixture for tests that run the component watcher: a fresh label
map and no thumbnail rendering. Its `:after` runs after an async test's
`done`, so it covers the whole test."
{:before (fn []
(cthi/reset-idmap!)
(install-thumbnail-noop!))
:after restore-thumbnail!})
;; --------------------------------------------------------------------------
;; (1) Frontend realisation of operations: op record -> workspace event(s)
;;
;; The operation's "what" (its update-fn / target) is shared in common; this maps
;; it to the "how" on the frontend — the real event a user interaction dispatches.
;; Returns a vector of events to emit for that operation.
;; Operations as workspace events
;; --------------------------------------------------------------------------
;; The edit a ChangeProperty performs is the SHARED `n/set-property`, so the
;; frontend applies the identical change the common node does (only the wrapping
;; differs: a real workspace event here vs. apply-changes there).
(declare current-file)
(defn- add-child->shape
"Build the shape value AddChild introduces, parented under the target parent in
the current store page (mirrors the common add-child's sample shape). Returns
the shape with parent/frame set to the target parent."
[parent-label new-label shape-params]
(let [parent-id (cthi/id parent-label)
shape (cths/sample-shape new-label (or shape-params {}))]
(assoc shape
:parent-id parent-id
:frame-id parent-id)))
(defn- variant-action-events
"The workspace events of the `n/VariantAction` `op`."
[{:keys [action params]} situation]
(let [id #(tm/target-shape-id situation %)
member #(n/member-component situation (:set-name params) (:member params))
select #(dws/select-shapes (into (d/ordered-set) (map id) %))]
(case action
:transform
[(dwv/transform-in-variant (id (:target params)))]
:combine
(if (:selected? params)
[(select (:targets params))
(dwv/combine-selected-as-variants {:trigger "workspace:context-menu"})]
[(dwv/combine-as-variants (mapv id (:targets params)) {:trigger "workspace:context-menu"})])
:rename
[(dwv/rename-comp-or-variant-and-main (:id (n/component-of situation (:target params)))
(:name params))]
:rename-in-layers
(let [{:keys [id variant-id variant-properties]} (member)]
[(dwv/update-properties-names-and-values
id variant-id variant-properties
(mapv (fn [[name value]] {:name name :value value}) (:properties params)))])
:remove-empty
[(dwv/remove-empty-properties (n/variant-set-id situation (:set-name params)))]
:error
[(if-let [value (:value params)]
(dwv/update-error (:id (member)) value)
(dwv/update-error (:id (member))))]
:shortcut
[(select (:targets params))
(case (:kind params)
:create-component (dwv/add-component-or-variant)
:duplicate (dwv/duplicate-or-add-variant))])))
(defn op->events
"Map a comp operation record to the real workspace event(s) it dispatches.
`op` is one of the comp node records (app.common.test-helpers.composable.comp.nodes);
`situation` provides cross-file context (e.g. the library id) for ops that need
it.
Each operation is realised with the SAME production change builder the common
node uses, but wrapped in the real workspace event (so it commits to the store
and the watcher auto-propagates):
ChangeProperty -> update-shapes (generate-update-shapes; n/set-property)
MoveChild -> relocate-shapes (generate-relocate, existing shape)
AddChild -> add-shape (create a shape under the parent)
RemoveChild -> delete-shapes (generate-delete-shapes)
SyncFromLibrary -> sync-file (the cross-file library-update action, H)
Undo -> dwu/undo (reverse the previous operation(s), I)
(In-file propagation is automatic — the watcher — so no propagate op exists.)"
"The workspace events a user action dispatches for the comp operation `op`,
built from `situation` and from the same helpers the common node uses."
[op situation]
(cond
(instance? n/ChangeProperty op)
(let [{:keys [target property value]} op]
;; `target` may be a ROLE (resolved via the situation, so the edit follows
;; the role as make-nested-component re-points it) or a label — same dual resolution
;; as the common ChangeProperty. The edit uses the SHARED `n/set-property`.
[(dwsh/update-shapes #{(tm/target-shape-id situation target)}
(fn [shape] (n/set-property shape property value)))])
(let [{:keys [target property value]} op
id (tm/target-shape-id situation target)]
(if (= :margin property)
;; the sidebar's layout child margin
(let [shape (n/set-property {} property value)]
[(dwsl/update-layout-child [id] (select-keys shape [:layout-item-margin
:layout-item-margin-type]))])
[(dwsh/update-shapes #{id} (fn [shape] (n/set-property shape property value)))]))
(instance? n/EditText op)
;; the text editor's commit on blur, SVG renderer path
(let [{:keys [target edit value]} op
id (tm/target-shape-id situation target)
shape (tm/shape-by-id situation id)
{:keys [content name]} (n/text-edit-commit shape edit value)]
[(dwtx/v2-update-text-shape-content id content
:update-name? (some? name)
:name name
:finalize? true
:save-undo? true
:original-content (:content shape))])
(instance? n/Rotate op)
;; The real sidebar rotation event, absolute mode: rotates the shape (and its
;; whole subtree) around its center. Its apply-modifiers step runs the
;; placement-vs-override classification for component copies (check-delta),
;; which is part of what a case using `rotate` exercises.
;; the sidebar rotation, which decides what it touches in copies (check-delta)
(let [{:keys [target angle]} op]
[(dwt/increase-rotation [(tm/target-shape-id situation target)] angle)])
(instance? n/MoveShape op)
;; the sidebar position, in page coordinates
(let [{:keys [target dx dy]} op
id (tm/target-shape-id situation target)
{:keys [x y]} (:selrect (tm/shape-by-id situation id))]
[(dwt/update-position id {:x (+ x dx) :y (+ y dy)} {:absolute? true})])
(instance? n/ChangeHeight op)
;; The real sidebar dimension event.
;; the sidebar height
(let [{:keys [target value]} op]
[(dwt/update-dimensions [(tm/target-shape-id situation target)] :height value)])
(instance? n/SwapComponent op)
;; Swap lineage `name`'s nesting level `level` for lineage `target`'s component
;; via the REAL swap event (dwl/component-swap), so it commits through the
;; normal path and the watcher AUTOMATICALLY propagates the swap to copies
;; (incl. the deeper nesting levels). This is the behaviour under test.
(let [{:keys [name level target keep-touched?]} op
file-id (:id (tm/file situation))
nested (n/lineage-nesting situation name level)
shape (tm/shape-by-id situation (:nested-head nested))
target-id (n/lineage-component-id situation target)]
[(dwl/component-swap shape file-id target-id (boolean keep-touched?))])
(instance? n/SwapShape op)
(let [{:keys [target to keep-touched?]} op]
[(dwl/component-swap (tm/shape-by-id situation (tm/target-shape-id situation target))
(:id (tm/file situation))
(n/swap-target-id situation to)
(boolean keep-touched?))])
(instance? n/MoveToCell op)
;; the board's new cells, as a canvas drop commits them
(let [{:keys [board child row column]} op]
[(dwsh/update-shapes #{(tm/target-shape-id situation board)}
(n/move-to-cell-fn (tm/target-shape-id situation child) row column)
{:with-objects? true})])
(instance? n/SwitchVariant op)
;; The variant-switch action: switch the resolved variant copy head to the
;; sibling member whose selector property (pos 0) has `value`, via the REAL
;; `variants-switch` event (which discovers the sibling in the variant container
;; and routes through component-swap keep-touched? true, so the watcher
;; auto-propagates the switch across nesting levels exactly like a swap). `target`
;; uses the standard resolution (role | label | (situation -> id) fn), so the op
;; is structure-blind.
(let [{:keys [target value]} op
head-id (tm/target-shape-id situation target)
(let [head-id (tm/target-shape-id situation (:target op))
shape (tm/shape-by-id situation head-id)]
[(dwv/variants-switch {:shapes [shape] :pos 0 :val value})])
[(dwv/variants-switch {:shapes [shape]
:pos (n/switch-pos situation op)
:val (n/switch-value situation op)})])
(instance? n/ApplyToken op)
(let [data (:data (current-file))
token (-> (cfo/get-tokens-in-active-sets (cfo/get-tokens-status data)
(cfo/get-tokens-lib data))
(get (:token-name op)))]
[(dwta/apply-token {:shape-ids [(tm/target-shape-id situation (:target op))]
:attributes n/radius-attrs
:token token
:on-update-shape dwta/update-shape-radius})])
(instance? n/UnapplyToken op)
[(dwta/unapply-token {:shape-ids [(tm/target-shape-id situation (:target op))]
:attributes n/radius-attrs
:token-name (:token-name op)})]
(instance? n/VariantAction op)
(variant-action-events op situation)
(instance? n/AddVariant op)
[(dwv/add-new-variant (:id (n/member-root situation (:set-name op) (:member op))))]
(instance? n/EditVariantProperty op)
;; the design tab's variant property edits
(let [[edit & args] (n/variant-property-call situation op)]
[(case edit
:add (let [[variant-id opts] args]
(dwv/add-new-property variant-id opts))
:remove (apply dwv/remove-property args)
:rename (let [[variant-id pos name] args]
(dwv/update-property-name variant-id pos name {:trigger "workspace:design-tab"}))
:reorder (apply dwv/reorder-variant-poperties args)
:set-value (apply dwv/update-property-value args))])
(instance? n/Detach op)
[(dwl/detach-component (tm/target-shape-id situation (:target op)))]
(instance? n/ResetOverrides op)
[(dwl/reset-component (tm/target-shape-id situation (:target op)))]
(instance? n/UpdateMain op)
[(dwl/update-component-sync (tm/target-shape-id situation (:target op))
(:id (tm/file situation)))]
(instance? n/DeleteComponent op)
(let [root (tm/shape-by-id situation (tm/target-shape-id situation (:target op)))]
[(dwl/delete-component {:id (:component-id root)})])
(instance? n/Duplicate op)
[(dws/duplicate-shapes #{(tm/target-shape-id situation (:target op))}
:change-selection? false)]
(instance? n/PasteToRoot op)
;; the clipboard's copy of the shape, pasted with the root selected
(let [file (current-file)
page (get-in file [:data :pages-index (:current-page-id @st/state)])
data (thp/simulate-copy-shape #{(tm/target-shape-id situation (:target op))}
(:objects page) {(:id file) file} page file
#{"components/v2"} 46)]
[(dws/select-shape uuid/zero)
(dw/paste-shapes data)])
(instance? n/NestCopy op)
(let [parent-id (tm/target-shape-id situation (:into op))
copy-id (tm/target-shape-id situation (:copy op))
index (n/nest-target-index situation parent-id)]
(if-let [cell (:cell op)]
;; the canvas drop into a grid cell
[(dwt/move-shapes-to-frame #{copy-id} parent-id index cell)]
[(dwsh/relocate-shapes #{copy-id} parent-id index)]))
(instance? n/RestoreComponent op)
[(dwl/restore-component (:id (tm/file situation))
(n/deleted-component-id situation (:deletion op)))]
(instance? n/MoveChild op)
(let [{:keys [target parent to-index]} op]
[(dwsh/relocate-shapes #{(cthi/id target)} (cthi/id parent) to-index)])
[(dwsh/relocate-shapes #{(tm/resolve-shape-id situation target)}
(tm/resolve-shape-id situation parent)
to-index)])
(instance? n/RemoveChild op)
(let [{:keys [target]} op]
[(dwsh/delete-shapes #{(cthi/id target)})])
[(dwsh/delete-shapes #{(tm/resolve-shape-id situation (:target op))})]
(instance? n/AddChild op)
(let [{:keys [parent new-label shape-params]} op]
[(dwsh/add-shape (add-child->shape parent new-label shape-params)
(let [{:keys [parent new-label shape-params]} op
parent (tm/resolve-shape situation parent)]
[(dwsh/add-shape (n/child-shape parent new-label shape-params)
{:no-select? true})])
(instance? n/SyncFromLibrary op)
;; The cross-file library-update action: sync the current (consuming) file
;; from its linked library — exactly what the "library updated" dialog does.
(let [file-id (:current-file-id @st/state)
library-id (first (keys (tm/aux-files situation)))]
[(dwl/sync-file file-id library-id)])
;; the library update the "library updated" dialog runs
[(dwl/sync-file (:current-file-id @st/state) (n/library-id situation))]
(instance? n/Undo op)
;; Reverse the previous operation(s) via the real undo event. The workspace
;; undo stack was maintained automatically by the prior ops' commits.
[dwu/undo]
(vec (repeat (:times op) dwu/undo))
(instance? n/UndoBeforeSync op)
;; emitted together, so the undo commits before the watcher inspects the edit
(let [{:keys [target property value]} op]
[(dwsh/update-shapes #{(tm/target-shape-id situation target)}
(fn [shape] (n/set-property shape property value)))
dwu/undo])
(instance? n/Redo op)
[dwu/redo]
:else
(throw (ex-info (str "op->events: no frontend realisation for " (pr-str (type op)))
{:op op}))))
;; --------------------------------------------------------------------------
;; (2) Async interpreter
;; Interpreter
;; --------------------------------------------------------------------------
(def ^:private settle-debounce-ms
"Resolve a step once the store's commit stream has been idle this long. This
captures the edit commit AND the watcher's follow-up sync commit, without a
fixed total delay. (Provisional: a fully deterministic per-op stopper would
await that op's specific component-changed/sync; debounce-idle is robust enough
for now.)"
60)
(def ^:private settle-timeout-ms 2000)
;; Longest a step may take to settle; a step that takes longer fails.
(def ^:private step-timeout-ms 2000)
(defn- install-situation-event
"An UpdateEvent installing the situation's files into the (global) store: the
primary file as the current/workspace file, plus any AUXILIARY files (e.g. a
linked library, for the cross-file case H) alongside in `:files`, each tagged
`:library-of` the current file so the library-sync machinery treats them as
linked libraries."
"An event that installs the situation's file as the current one, its
auxiliary files as linked libraries, and an empty undo stack, so an undo
never reaches the previous variant's entries."
[situation]
(let [file (tm/file situation)
aux (tm/aux-files situation)]
@ -241,54 +329,128 @@
:current-file-id (:id file)
:current-page-id (cthf/current-page-id file)
:permissions {:can-edit true}
:workspace-undo {}
:files (into {(:id file) file}
(map (fn [[lib-id lib]] [lib-id (assoc lib :library-of (:id file))]))
aux))))))
(defn current-file
"Read the live workspace file out of the global store."
"The current file in the global store."
[]
(let [st @st/state]
(get-in st [:files (:current-file-id st)])))
(defn- await-settle
"Dispatch `events` into the global store, then call `k` once the commit stream
has gone idle (debounced). A hard timeout guarantees progress."
[events k]
(let [stream (ptk/input-stream st/state)
commits (->> stream (rx/filter dch/commit?))
;; resolve on first idle gap after a commit, or on timeout
settled (->> commits
(rx/debounce settle-debounce-ms)
(rx/take 1)
(rx/timeout settle-timeout-ms (rx/of :settle/timeout)))]
(rx/subscribe settled (fn [_] (k)))
(doseq [e events] (st/emit! e))))
(defn fill-of
"The fill color of the shape `label` in the live file."
[label]
(-> (cths/get-shape (current-file) label) :fills first :fill-color))
(defn fill-commit
"A commit that fills the shape `label` of the live file with `color`, with
`opts` merged into the commit params."
[label color opts]
(let [page (cthf/current-page (current-file))
changes (cls/generate-update-shapes
(pcb/empty-changes nil (:id page))
#{(cthi/id label)}
#(assoc % :fills (cths/sample-fills-color :fill-color color))
(:objects page)
{})]
(dch/commit-changes (merge {:redo-changes (:redo-changes changes)
:undo-changes (:undo-changes changes)}
opts))))
(defn- await-ready
"A promise that resolves with true once `ready?` holds, polling, or with
false after `timeout-ms`."
[ready? timeout-ms]
(let [start (js/Date.now)]
(js/Promise.
(fn [resolve]
(letfn [(poll []
(cond
(ready?) (resolve true)
(> (- (js/Date.now) start) timeout-ms) (resolve false)
:else (js/setTimeout poll 5)))]
(poll))))))
(defn await-step
"Emit `events` and return a promise of `:settled` once the pending work of
`app.main.data.workspace.reflow` drains (component sync, layout and text
reflow), as the plugin `waitForLayoutUpdate` waits; or of
`{:timeout pending}` after `timeout-ms` (default `step-timeout-ms`). Work
must be opened while the events are processed; for events that commit
only after asynchronous work that opens none (token resolution), pass
`ready?`, which must hold before the pending work is awaited."
([events] (await-step events step-timeout-ms))
([events timeout-ms] (await-step events timeout-ms nil))
([events timeout-ms ready?]
(doseq [e events] (st/emit! e))
(-> (if ready? (await-ready ready? timeout-ms) (js/Promise.resolve true))
(.then (fn [ready]
(if ready
(-> (pwrf/wait-for-layout-update nil timeout-ms)
(.then (constantly :settled))
(.catch (fn [_] {:timeout (wrf/pending)})))
{:timeout {:not-ready (wrf/pending)}}))))))
(defn- describe-pending
"The pending work map with the ids replaced by their test labels, if any."
[pending]
(update-keys pending #(or (cthi/label %) %)))
(defn- unwrap
"The concrete operation of an op unit: the op chosen by a RecordedChoice,
through nested choices (e.g. an optional one-of)."
[op]
(if (tm/recorded-choice? op) (recur (tm/choice-of op)) op))
(defn- record-choices
"Record in `situation` each choice on the way from the op unit `op` to its
concrete op, outermost first, as nested `RecordedChoice`s' own `apply-to`
does. Returns the situation."
[situation op]
(if (tm/recorded-choice? op)
(recur (tm/record-choice situation op) (tm/choice-of op))
situation))
(defn- record-op
"Record an operation's application onto the situation (after its effect settled),
re-reading the file from the store. For a RecordedChoice (one-of), record the
choice under the one-of identity (so the asserter's `get-choice` works) and
then the chosen op's application, in the order `RecordedChoice`'s own
`apply-to` uses."
"`situation` with the live file and the application of the settled op unit
`op`: its choices first, then the op's own fields and its
`n/applied-result`, if any."
[situation op]
(let [situation (tm/with-file situation (current-file))
[situation op] (if (tm/recorded-choice? op)
[(tm/record-choice situation op) (tm/choice-of op)]
[situation op])]
(tm/record-application situation op (dissoc (into {} op) ::tm/id))))
(let [before (tm/file situation)
situation (-> situation
(tm/with-file (current-file))
(record-choices op))
op (unwrap op)
record (cond-> (dissoc (into {} op) ::tm/id)
(satisfies? n/IAppliedResult op)
(merge (n/applied-result op before (tm/file situation))))]
(tm/record-application situation op record)))
(defn- op-events
"The workspace events to dispatch for an op unit (a plain op or a one-of's
RecordedChoice — for the latter, the chosen op's events). `situation` provides
cross-file context to ops that need it."
"The workspace events of the op unit `op` (for a choice, of the chosen op)."
[op situation]
(op->events (if (tm/recorded-choice? op) (tm/choice-of op) op) situation))
(op->events (unwrap op) situation))
(defn- live-shape
"The shape `id` of the current page of the live file."
[id]
(get-in (current-file) [:data :pages-index (:current-page-id @st/state) :objects id]))
(defn- op-ready
"For the op unit `op` whose events commit only after asynchronous work that
opens no pending work, a predicate of when they have committed; else nil."
[op situation]
(let [op (unwrap op)]
(when (instance? n/ApplyToken op)
(let [id (tm/target-shape-id situation (:target op))]
#(= (:token-name op) (get-in (live-shape id) [:applied-tokens :r1]))))))
(defn- install-file-event
"An UpdateEvent that replaces the current file in the (global) store with `file`
(keeping aux files and everything else). Used to write back the result of a
FILE-TRANSFORMING op (see `file-op?`)."
"An event that makes `file` the current file in the store, the result of a
`sync-op?` operation."
[file]
(ptk/reify ::install-file
ptk/UpdateEvent
@ -298,79 +460,175 @@
:current-page-id (cthf/current-page-id file))
(assoc-in [:files (:id file)] file)))))
;; --------------------------------------------------------------------------
;; Undo/redo round trip (see `app.common.test-helpers.composable.comp.undo-check`)
;;
;; Run on every user step that dispatches events: undo gives back the file
;; and the undo index before the step, redo those after it, so a step adds
;; exactly one undo entry or group. File installs (`sync-op?`) add none and
;; are the baseline the end-of-variant round trip undoes back to.
;; --------------------------------------------------------------------------
(defn- undo-index
"The workspace undo index: the entry the next undo reverts, -1 when none."
[]
(let [{:keys [index items]} (:workspace-undo @st/state)]
(or index (dec (count items)))))
(defn- snapshot
"The normalized live file the round trip compares. WASM regenerates
`:position-data` by measuring, so it is left out there."
[]
(uc/snapshot (current-file)
{:position-data? (not (features/active-feature? @st/state "render-wasm/v1"))}))
(defn- mark-baseline
[situation]
(uc/mark-baseline situation (undo-index) (snapshot)))
(defn- settle!
"Emit `event` and wait for it to settle. Resolves with nil, or with the
reason it did not settle."
[event]
(.then (await-step [event])
(fn [result]
(when-not (= :settled result)
(str "did not settle; pending: " (pr-str (describe-pending (:timeout result))))))))
(defn- round-trip-move
"Emit `event` (undo or redo) and check that the file equals the snapshot
`expected` and the undo index `expected-index`, recording failures of
`phase` at `step`. Resolves with `[situation settled?]`."
[situation event step phase expected expected-index]
(.then (settle! event)
(fn [error]
(if error
[(uc/add-error situation step phase error) false]
[(-> situation
(uc/compare-states step phase expected (snapshot))
(uc/compare-index step (keyword (str (name phase) "-index"))
expected-index (undo-index)))
true]))))
(defn- check-step
"The round trip of user step `op`, given the snapshot `before` and the undo
index `index-before` taken before it. Resolves with the situation."
[situation op before index-before]
(let [step (uc/step situation op)
after (snapshot)
index-after (undo-index)]
(if (= index-before index-after)
(js/Promise.resolve (uc/compare-states situation step :no-undo-entry before after))
(.then (round-trip-move situation dwu/undo step :undo before index-before)
(fn [[situation settled?]]
(if settled?
(.then (round-trip-move situation dwu/redo step :redo after index-after)
first)
situation))))))
(defn- repeat-move
"Emit `event` (undo or redo) until `done?` holds, at most `limit` times.
Resolves with `[situation times]`, `situation` holding a failure of
`phase` when a move did not settle."
[situation event phase done? limit]
(letfn [(step [times]
(if (or (done?) (>= times limit))
(js/Promise.resolve [situation times])
(.then (settle! event)
(fn [error]
(if error
[(uc/add-error situation nil phase error) times]
(step (inc times)))))))]
(step 0)))
(defn- check-variant
"The end-of-variant round trip: undo back to the baseline, then redo as many
times. Resolves with the situation."
[situation]
(let [{:keys [depth] :as baseline} (uc/baseline situation)
final (snapshot)
final-index (undo-index)
limit (- final-index depth)]
(if (pos? limit)
(.then (repeat-move situation dwu/undo :variant-undo #(<= (undo-index) depth) limit)
(fn [[situation times]]
(let [situation (uc/compare-states situation nil :variant-undo
(:snapshot baseline) (snapshot))]
(.then (repeat-move situation dwu/redo :variant-redo
#(>= (undo-index) final-index) times)
(fn [[situation _]]
(uc/compare-states situation nil :variant-redo final (snapshot)))))))
(js/Promise.resolve situation))))
(defn- sync-op?
"Whether `op` is a SYNCHRONOUS, `apply-to`-based operation rather than one that
dispatches a workspace event and needs settling. Two kinds:
- FILE-TRANSFORMING: the `:assembly` nodes (see `n/IComponentOperation`) and
`skip`, which arrange the CONFIGURATION (create, nest, instantiate,
re-point roles) — applied by running `apply-to` against the live store
file and writing the result back. The property under test is still
exercised by the SUBSEQUENT real-event ops.
- `Test`: an inline assertion checkpoint — its `apply-to` runs the assertion
against the current situation and returns it unchanged.
Both are handled by `run-sync-op` (no async settle — any store write is a
synchronous UpdateEvent)."
"Whether the op unit `op` runs its `apply-to` on the live file instead of
dispatching events: assembly nodes, `skip` and inline tests."
[op]
(let [op (if (tm/recorded-choice? op) (tm/choice-of op) op)]
(let [op (unwrap op)]
(or (instance? tm/Skip op)
(instance? tm/Test op)
(= :assembly (n/op-kind op))
;; A user operation, but the real reset event transitively reads browser
;; globals (CSS vars), so it cannot run headless; the shared apply-to runs
;; the production reset generator with validation off.
(instance? n/ResetCopyInstance op))))
(= :assembly (n/op-kind op)))))
(defn- run-sync-op
"Apply a synchronous (`sync-op?`) operation: run its shared `apply-to` against a
situation whose `:file` is the live store file, write the resulting file back
into the store, and return the updated situation (with any re-pointed roles).
For `Test` this runs the inline assertion (against the live store state) and the
file is unchanged; for `make-nested-component`/`skip` it writes back the transformed file.
Synchronous."
"Run the `apply-to` of the `sync-op?` op unit `op` on the live file and
install the result. Returns the situation."
[situation op]
(let [situation (tm/with-file situation (current-file))
situation (tm/apply-to op situation)]
(st/emit! (install-file-event (tm/file situation)))
situation))
(defn- op-grace-ms
"Extra wait AFTER an event-op has settled, before proceeding. Always zero:
the `rx/timer` and `rp/cmd!` calls that `SyncFromLibrary` schedules are
mocked (see `check`) so they fire instantly and succeed."
[_op]
0)
;; a file install is the round trip's new baseline; a skipped optional
;; and an inline test install nothing new
(cond-> situation
(and (::undo-check? situation)
(not (instance? tm/Test (unwrap op)))
(not (instance? tm/Skip (unwrap op))))
(mark-baseline))))
(defn- run-ops
"Async fold over `ops` (concrete operation units, in order — plain ops and/or
one-of RecordedChoice wrappers). Threads the situation. A SYNCHRONOUS op
(`sync-op?` — file-transforming or an inline `Test`) is applied synchronously
via `apply-to`; every other op dispatches its real workspace event(s) and awaits
settlement (plus a per-op grace period, see `op-grace-ms`). The file is re-read
from the store after each. Calls `k` with the final situation."
"Run the op units `ops` in order, each `sync-op?` one on the live file and
the others as events awaited with `await-step`. Calls `k` with the final
situation, or with nil after failing the test when a step did not
settle."
[situation ops k]
(if (empty? ops)
(k situation)
(let [op (first ops)]
(let [op (first ops)
kind (let [op (unwrap op)]
(when (satisfies? n/IComponentOperation op)
(n/op-kind op)))
check-step? (and (::undo-check? situation)
(contains? #{:user :frontend-only} kind))
before (when check-step? (snapshot))
index-before (undo-index)]
(if (sync-op? op)
(run-ops (run-sync-op situation op) (rest ops) k)
(await-settle
(op-events op situation)
(fn []
(let [continue #(run-ops (record-op situation op) (rest ops) k)
grace (op-grace-ms op)]
(if (pos? grace)
(js/setTimeout continue grace)
(continue)))))))))
(.then (await-step (op-events op situation) step-timeout-ms (op-ready op situation))
(fn [result]
(if (= :settled result)
(let [situation (record-op situation op)]
(cond
check-step?
(.then (check-step situation (unwrap op) before index-before)
#(run-ops % (rest ops) k))
;; never undo past the state a case's own undo went back to
(and (::undo-check? situation)
(= :undo kind)
(< (undo-index) (:depth (uc/baseline situation))))
(run-ops (mark-baseline situation) (rest ops) k)
:else
(run-ops situation (rest ops) k)))
(do
(t/is false (str "Step did not settle in " step-timeout-ms "ms: "
(pr-str (type (unwrap op)))
"; pending: " (pr-str (describe-pending (:timeout result)))))
(k nil)))))))))
(defonce ^:private original-store
;; Captured at namespace-LOAD time — i.e. before any test in the run executes.
;; Several test namespaces (the plugins suite) `set!` st/state / st/stream to
;; isolated stores and never restore them. That silently kills this harness:
;; the refs in `app.main.refs` (through which `watch-component-changes`
;; observes commits) are okulary lenses bound to THIS atom instance at load
;; time, so once the var points elsewhere, our events commit to a store the
;; watcher does not see and propagation dies with no error. Re-installing the
;; original per variant makes the harness immune to run order.
;; The store at load time. Some test namespaces `set!` st/state and
;; st/stream and never restore them, while the `app.main.refs` lenses the
;; component watcher reads stay bound to these atoms.
{:state st/state :stream st/stream})
(defn- restore-global-store!
@ -380,53 +638,79 @@
(set! st/state (:state original-store))
(set! st/stream (:stream original-store)))
(defn- headless-text-measurement
"Stands in for the DOM text measurement, which needs a browser. A text whose
content changes stays pending until the renderer starts measuring it (see
`app.main.data.workspace.texts`); this starts and ends that measurement
for each text a `:text/reflow` names, leaving its geometry and
`:position-data` as they are. Replaces itself when started again."
[]
(ptk/reify ::headless-text-measurement
ptk/WatchEvent
(watch [_ _ stream]
(->> stream
(rx/filter (ptk/type? :text/reflow))
(rx/map deref)
;; after the text watcher opened its wait for the measurement
(rx/observe-on :async)
(rx/tap (fn [{:keys [ids]}]
(wrf/finish! (wrf/start! :text-measure ids))))
(rx/ignore)
(rx/take-until (rx/filter (ptk/type? ::headless-text-measurement) stream))))))
(defn install!
"Install `situation` in the global store and start the watchers the workspace
starts, replacing the previous variant's. Restores the global store first (a
preceding namespace may have swapped it). Returns the situation."
starts, replacing the previous variant's, plus the headless stand-in for
the DOM text measurement. Restores the global store first (a preceding
namespace may have swapped it) and forgets any pending work left over, so a
step that timed out earlier cannot hold up this variant's steps. Stopping
the previous layout watcher clears it too, but on the first install of a run
there is none. Returns the situation."
[situation]
(restore-global-store!)
(wrf/reset-pending!)
(st/emit! (install-situation-event situation)
(dw/finalize-edit-watchers)
(dw/initialize-edit-watchers)
(dwl/watch-library-changes))
(dwl/watch-library-changes)
(headless-text-measurement))
situation)
(defn- run-variant
"Set up one variant on the global store and run its ops. `setup` returns a
situation (file + roles). Calls `k` with the final situation."
[setup ops k]
;; fresh label space per variant (mirrors the pure `tm/run-all`)
situation (file + roles). With `undo-check?`, runs the undo/redo round
trip of each user step and of the variant. Calls `k` with the final
situation, or nil when a step did not settle."
[setup ops undo-check? k]
;; a fresh label map per variant, as `tm/run-all` does
(cthi/reset-idmap!)
(run-ops (install! (setup)) ops k))
(let [situation (-> (setup)
(assoc ::undo-check? undo-check?)
(uc/with-runner :frontend)
(install!))]
(run-ops (cond-> situation undo-check? (mark-baseline))
ops
(fn [situation]
(if (and situation undo-check?)
(.then (check-variant situation) k)
(k situation))))))
;; --------------------------------------------------------------------------
;; (3) Test-facing check
;; Test entry point
;; --------------------------------------------------------------------------
(defn check
"Frontend `check`: run `case-map` ({:setup :operation}) through the REAL app and,
if `asserter` is given, apply it (a situation -> any fn performing assertions)
to the resulting situation of EACH enumerated variant. Async — `done` is the
cljs.test async callback and MUST be called when finished.
Assertions may be INLINE (via `Test` operations in the `:operation` sequence,
firing as the op runs) and/or via the trailing `asserter`; `asserter` is
optional (omit when all assertions are inline). The asserter closes over node
references the test holds (e.g. `has-property-of` on a change node). In-file
propagation is AUTOMATIC (the watcher) — no propagate op is added.
Mocks are installed for the duration of the check: `rp/cmd!` returns
success (recording calls) and `rx/timer` fires instantly, so the
`SyncFromLibrary` op's delayed RPC does not produce network errors.
Arities: `(check done case-map)`, which takes the asserter from the case
map's `:asserter`, or `(check done case-map asserter)`."
"Run every variant of `case-map` through the frontend, apply `asserter`
(default the case map's `:asserter`) to each result and check its undo/redo
round trip (`app.common.test-helpers.composable.comp.undo-check`). Calls the
async test's `done` at the end. RPC calls are mocked, `rx/timer` fires at
once, for the delayed RPC of the library update, and DOM lookups find
nothing, for the delayed focus after adding a variant."
([done case-map] (check done case-map (:asserter case-map)))
([done {:keys [setup operation]} asserter]
([done {:keys [setup operation] :as case-map} asserter]
(mock/with-mocks
{rp/cmd! mock/rpc-cmd-mock
rx/timer mock/timer-mock}
{rp/cmd! mock/rpc-cmd-mock
rx/timer mock/timer-mock
dom/get-element (constantly nil)}
(fn [inner-done]
(let [variants (tm/enumerate operation)]
(letfn [(run-next [vs]
@ -434,14 +718,14 @@
(inner-done)
(run-variant
setup
;; a variant is a composed operation; flatten to its ordered leaf
;; ops. `enumerate` already removed all one-of choices, so the
;; variant is a Sequence (or a single op).
(tm/sequence-ops (first vs))
(uc/enabled? case-map)
(fn [situation]
(when asserter
(when situation
(t/testing (str "operations:\n " (tm/describe-applied situation))
(asserter situation)))
(when asserter
(asserter situation))
(uc/check! situation case-map)))
(run-next (rest vs))))))]
(run-next variants))))
done)))

View File

@ -0,0 +1,37 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.data.changes-test
(:require
[app.common.files.changes-builder :as pcb]
[app.common.test-helpers.composable.comp.setups :as setup]
[app.common.test-helpers.ids-map :as thi]
[app.main.data.changes :as dch]
[app.main.store :as st]
[app.plugins.reflow :as pwrf]
[cljs.test :as t :include-macros true]
[frontend-tests.composable-tests.interpreter :as ftm]))
(t/use-fixtures :each ftm/fixture)
(t/deftest change-without-page-leaves-the-pages-alone
(t/async done
(ftm/install! (setup/simple-component-with-copy))
(let [file (ftm/current-file)
pages (set (keys (get-in file [:data :pages-index])))
changes (-> (pcb/empty-changes)
(pcb/with-library-data (:data file))
(pcb/update-component (thi/id :component1)
#(assoc % :annotation "Note")))]
(st/emit! (dch/commit-changes {:redo-changes (:redo-changes changes)
:undo-changes (:undo-changes changes)}))
(-> (pwrf/wait-for-layout-update nil 2000)
(.then (fn []
(let [data (:data (ftm/current-file))]
(t/is (= "Note" (get-in data [:components (thi/id :component1) :annotation])))
(t/is (= pages (set (keys (:pages-index data))))))))
(.catch #(t/is false (str "the commit did not settle: " %)))
(.finally done)))))

View File

@ -0,0 +1,41 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.data.workspace-edit-watchers-test
"Tests the lifecycle of the workspace edit watchers
(`dw/initialize-edit-watchers`): starting them again, as a file reload
does, replaces the running ones instead of adding a second set."
(:require
[app.common.test-helpers.composable.comp.setups :as setup]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[app.main.data.workspace :as dw]
[app.main.data.workspace.shapes :as dwsh]
[app.main.store :as st]
[cljs.test :as t :include-macros true]
[frontend-tests.composable-tests.interpreter :as ftm]))
(t/use-fixtures :each ftm/fixture)
(defn- undo-entries-for-an-edit
"Install a component with a copy, start the edit watchers `starts` times,
edit the main child and resolve with the number of undo entries added."
[starts]
(ftm/install! (setup/simple-component-with-labeled-copy))
(dotimes [_ (dec starts)]
(st/emit! (dw/initialize-edit-watchers)))
(swap! st/state dissoc :workspace-undo)
(-> (ftm/await-step
[(dwsh/update-shapes #{(thi/id :main-child)}
#(assoc % :fills (ths/sample-fills-color :fill-color "#ff0000")))])
(.then (fn [_]
(count (get-in @st/state [:workspace-undo :items]))))))
(t/deftest ^:async restarted-edit-watchers-record-each-commit-once
(let [once (await (undo-entries-for-an-edit 1))
twice (await (undo-entries-for-an-edit 2))]
(t/is (pos? once))
(t/is (= once twice))))

View File

@ -0,0 +1,220 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.data.workspace-libraries-test
"The library events that act on several shapes or components at once, each
as one undo entry, and the branches of the single-shape events that the
composable cases do not reach: creating or placing a component with an
id ref, a blank rename and updating a main that lives in a linked
library."
(:require
[app.common.data :as d]
[app.common.geom.point :as gpt]
[app.common.test-helpers.components :as cthc]
[app.common.test-helpers.composable.core :as tm]
[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.common.types.component :as ctk]
[app.common.types.components-list :as ctkl]
[app.main.data.workspace.libraries :as dwl]
[app.main.data.workspace.selection :as dws]
[app.main.data.workspace.shapes :as dwsh]
[app.main.data.workspace.undo :as dwu]
[app.main.store :as st]
[cljs.test :as t :include-macros true]
[frontend-tests.composable-tests.interpreter :as ftm]))
(t/use-fixtures :each ftm/fixture)
(def ^:private main-color "#111111")
(def ^:private override "#222222")
(defn- two-components
"Components :c1 and :c2, two copies of :c1 (:copy-a, :copy-b) and two plain
rects."
[]
(-> (cthf/sample-file :file1)
(ctho/add-simple-component :c1 :main1 :main1-child
:child-params {:fills (cths/sample-fills-color :fill-color main-color)})
(ctho/add-simple-component :c2 :main2 :main2-child)
(cthc/instantiate-component :c1 :copy-a :children-labels [:copy-a-child])
(cthc/instantiate-component :c1 :copy-b :children-labels [:copy-b-child])
(ctho/add-rect :rect-a)
(ctho/add-rect :rect-b)))
(defn- install-file!
[file]
(ftm/install! (tm/make-situation file)))
(defn- shape
[label]
(cths/get-shape (ftm/current-file) label))
(defn- shape-by-id
[id]
(cths/get-shape-by-id (ftm/current-file) id))
(defn- data
[]
(:data (ftm/current-file)))
(defn- undo-entries
[]
(count (get-in @st/state [:workspace-undo :items])))
(defn- step
"Run `events` and wait until their work drains."
[& events]
(ftm/await-step (vec events)))
(defn- select
[& labels]
(dws/select-shapes (into (d/ordered-set) (map cthi/id) labels)))
(defn- linked?
[label]
(some? (:component-id (shape label))))
(defn- fill
[label]
(-> (shape label) :fills first :fill-color))
(defn- set-fill
[& labels]
(dwsh/update-shapes (into #{} (map cthi/id) labels)
#(assoc % :fills (cths/sample-fills-color :fill-color override))))
(defn- component-count
[]
(count (ctkl/components-seq (data))))
(t/deftest ^:async detach-components-is-one-undo-entry
(install-file! (two-components))
(let [before (undo-entries)]
(t/is (= :settled (await (step (dwl/detach-components [(cthi/id :copy-a) (cthi/id :copy-b)])))))
(t/is (not (linked? :copy-a)))
(t/is (not (linked? :copy-b)))
(t/is (= (inc before) (undo-entries)))
(await (step dwu/undo))
(t/is (linked? :copy-a))
(t/is (linked? :copy-b))))
(t/deftest ^:async detach-selected-components
(install-file! (two-components))
(t/testing "nothing happens when a selected shape is inside a copy"
(await (step (select :copy-a :copy-b-child) dwl/detach-selected-components))
(t/is (linked? :copy-a))
(t/is (some? (:shape-ref (shape :copy-b-child)))))
(t/testing "the selected copies are detached"
(await (step (select :copy-a :copy-b) dwl/detach-selected-components))
(t/is (not (linked? :copy-a)))
(t/is (not (linked? :copy-b)))))
(t/deftest ^:async reset-components-is-one-undo-entry
(install-file! (two-components))
(await (step (set-fill :copy-a-child :copy-b-child)))
(t/is (= override (fill :copy-a-child)))
(let [before (undo-entries)]
(await (step (dwl/reset-components [(cthi/id :copy-a) (cthi/id :copy-b)])))
(t/is (= main-color (fill :copy-a-child)))
(t/is (= main-color (fill :copy-b-child)))
(t/is (= (inc before) (undo-entries)))
(await (step dwu/undo))
(t/is (= override (fill :copy-a-child)))
(t/is (= override (fill :copy-b-child)))))
(defn- copies-of
[component-label]
(->> (vals (:objects (cthf/current-page (ftm/current-file))))
(filter #(and (ctk/instance-head? %)
(not (ctk/main-instance? %))
(= (cthi/id component-label) (:component-id %))))))
(t/deftest ^:async multi-swap-is-one-undo-entry
(install-file! (two-components))
(let [before (undo-entries)]
(await (step (dwl/component-multi-swap [(shape :copy-a) (shape :copy-b)]
(:id (ftm/current-file))
(cthi/id :c2))))
(t/is (= 0 (count (copies-of :c1))))
(t/is (= 2 (count (copies-of :c2))))
(t/is (= (inc before) (undo-entries)))
(await (step dwu/undo))
(t/is (= 2 (count (copies-of :c1))))
(t/is (= 0 (count (copies-of :c2))))))
(t/deftest ^:async add-multiple-components-is-one-undo-entry
(install-file! (two-components))
(let [before (undo-entries)]
(await (step (select :rect-a :rect-b) (dwl/add-multiple-components)))
(t/is (= 4 (component-count)))
(t/is (= (inc before) (undo-entries)))
(await (step dwu/undo))
(t/is (= 2 (component-count)))))
(t/deftest ^:async add-multiple-components-skips-copies
(install-file! (two-components))
(await (step (select :rect-a :copy-a-child) (dwl/add-multiple-components)))
(t/is (= 2 (component-count))))
(t/deftest ^:async add-component-sets-the-id-ref
(install-file! (two-components))
(let [id-ref (atom nil)]
(await (step (dwl/add-component id-ref [(cthi/id :rect-a)])))
(t/is (some? (ctkl/get-component (data) @id-ref)))))
(t/deftest ^:async duplicate-component-makes-a-new-main
(install-file! (two-components))
(await (step (dwl/duplicate-component (:id (ftm/current-file)) (cthi/id :c1))))
(let [new-component (->> (ctkl/components-seq (data))
(remove #(#{(cthi/id :c1) (cthi/id :c2)} (:id %)))
first)]
(t/is (= 3 (component-count)))
(t/is (some? (shape-by-id (:main-instance-id new-component))))))
(t/deftest ^:async restore-components-is-one-undo-entry
(install-file! (two-components))
(let [file-id (:id (ftm/current-file))]
(await (step (dwl/delete-component {:id (cthi/id :c1)})
(dwl/delete-component {:id (cthi/id :c2)})))
(t/is (= 0 (component-count)))
(let [before (undo-entries)]
(await (step (dwl/restore-components {(cthi/id :c1) file-id
(cthi/id :c2) file-id})))
(t/is (= 2 (component-count)))
(t/is (= (inc before) (undo-entries))))))
(t/deftest ^:async update-component-of-a-library-main
(let [library (-> (cthf/sample-file :library :is-shared true)
(ctho/add-simple-component :lib-c :lib-main :lib-main-child))
file (-> (cthf/sample-file :file1)
(cthc/instantiate-component :lib-c :copy
:library library
:children-labels [:copy-child]))]
(ftm/install! (-> (tm/make-situation file)
(tm/with-aux-files {(:id library) library})))
(await (step (set-fill :copy-child)))
(await (step (dwl/update-component (cthi/id :copy))))
(let [library' (get-in @st/state [:files (:id library)])]
(t/is (= override (-> (cths/get-shape library' :lib-main-child) :fills first :fill-color))))
(t/testing "a shape that is not a head is left as it is"
(await (step (dwl/update-component (cthi/id :copy-child))))
(t/is (= override (fill :copy-child))))))
(t/deftest ^:async rename-component-to-a-blank-name
(install-file! (two-components))
(let [before (:name (ctkl/get-component (data) (cthi/id :c1)))]
(await (step (dwl/rename-component (cthi/id :c1) " ")))
(t/is (= before (:name (ctkl/get-component (data) (cthi/id :c1)))))))
(t/deftest ^:async instantiate-component-sets-the-id-ref
(install-file! (two-components))
(let [id-ref (atom nil)]
(await (step (dwl/instantiate-component (:id (ftm/current-file)) (cthi/id :c2)
(gpt/point 0 0) {:id-ref id-ref :origin "plugin"})))
(t/is (= (cthi/id :c2) (:component-id (shape-by-id @id-ref))))))

View File

@ -0,0 +1,189 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.data.workspace-library-links-test
"Linking a library to the file and unlinking it, with the libraries it
brings along, and publishing the file as a shared library. The server is
mocked."
(:require
[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.variants :as cthv]
[app.main.data.workspace.libraries :as dwl]
[app.main.repo :as rp]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
[frontend-tests.helpers.mock :as mock]
[frontend-tests.helpers.state :as ths]
[potok.v2.core :as ptk]))
(t/use-fixtures :each {:before cthi/reset-idmap!})
(defn- rpc
"A mock of `rp/cmd!` that answers each command from `responses`
(command -> value, or fn of the params returning an observable), and
records the calls in `calls`."
[calls responses]
(mock/stub
(fn [cmd params & _]
(swap! calls conj [cmd params])
(let [response (get responses cmd)]
(if (fn? response)
(response params)
(rx/of response))))))
(defn- commands
[calls]
(set (map first @calls)))
(defn- merge-state
"An event that merges `m` into the state, for what the workspace loads
before these events run."
[m]
(ptk/reify ::merge-state
ptk/UpdateEvent
(update [_ state]
(merge-with merge state m))))
(defn- files
[]
{:file (cthf/sample-file :file1)
:library (-> (cthf/sample-file :library :is-shared true)
(ctho/add-simple-component :lib-c :lib-main :lib-main-child))
:dependency (-> (cthf/sample-file :dependency :is-shared true)
(ctho/add-simple-component :dep-c :dep-main :dep-main-child))})
(defn- linked-to
[state file-id]
(->> (vals (:files state))
(filter #(= file-id (:library-of %)))
(map :id)
set))
(t/deftest link-loads-the-library-and-its-dependencies
(t/async
done
(let [{:keys [file library dependency]} (files)
by-id (into {} (map (juxt :id identity)) [library dependency])
calls (atom [])]
(mock/with-mocks
{rp/cmd! (rpc calls {:link-file-to-library [(:id dependency)]
:get-file #(rx/of (get by-id (:id %)))
:get-file-object-thumbnails {"thumbnail-id" "thumbnail-uri"}
:get-library-usage {:used-in 3}})}
(fn [inner-done]
(ths/run-store
(ths/setup-store file) inner-done
[(merge-state {:shared-files {(:id library) {:library-summary {:variants [{} {}]}}}})
(dwl/link-file-to-library (:id file) (:id library))]
(fn [state]
(t/is (= #{(:id library) (:id dependency)} (linked-to state (:id file))))
(t/is (= "thumbnail-uri" (get-in state [:thumbnails "thumbnail-id" :uri])))
(t/testing "a library with variants asks how much it is used"
(t/is (contains? (commands calls) :get-library-usage))))))
done))))
(t/deftest link-skips-libraries-already-loaded
(t/async
done
(let [{:keys [file library dependency]} (files)
calls (atom [])]
(mock/with-mocks
{rp/cmd! (rpc calls {:link-file-to-library [(:id dependency)]
:get-file #(rx/of library)
:get-file-object-thumbnails {}})}
(fn [inner-done]
(ths/run-store
(ths/setup-store file {:libraries [dependency]}) inner-done
[(dwl/link-file-to-library (:id file) (:id library))]
(fn [_]
(t/is (= [(:id library)]
(->> @calls
(filter #(= :get-file (first %)))
(map (comp :id second)))))
(t/is (not (contains? (commands calls) :get-library-usage))))))
done))))
(t/deftest link-that-would-make-a-loop
(t/async
done
(let [{:keys [file library]} (files)
calls (atom [])]
(mock/with-mocks
{rp/cmd! (rpc calls {:link-file-to-library
(fn [_] (rx/throw (ex-info "loop" {:code :circular-library-reference})))})}
(fn [inner-done]
(ths/run-store
(ths/setup-store file) inner-done
[(dwl/link-file-to-library (:id file) (:id library))]
(fn [state]
(t/is (= :error (get-in state [:notification :level])))
(t/is (empty? (linked-to state (:id file)))))))
done))))
(t/deftest unlink-drops-the-library-and-what-it-brought
(t/async
done
(let [{:keys [file library dependency]} (files)
calls (atom [])]
(mock/with-mocks
{rp/cmd! (rpc calls {:unlink-file-from-library nil
:get-file-libraries []})}
(fn [inner-done]
(ths/run-store
(ths/setup-store file) inner-done
[(dwl/libraries-fetched (:id file) [library dependency])
(dwl/unlink-file-from-library (:id file) (:id library))]
(fn [state]
(t/is (empty? (linked-to state (:id file))))
(t/is (some? (get-in state [:files (:id file)]))))))
done))))
(t/deftest cleanup-keeps-the-libraries-still-linked
(t/async
done
(let [{:keys [file library dependency]} (files)]
(ths/run-store
(ths/setup-store file) done
[(dwl/libraries-fetched (:id file) [library dependency])
(dwl/cleanup-unlinked-libraries (:id file) [library])]
(fn [state]
(t/is (= #{(:id library)} (linked-to state (:id file)))))))))
(defn- share
[file shared? check]
(fn [done]
(let [calls (atom [])]
(mock/with-mocks
{rp/cmd! (rpc calls {:set-file-shared nil})}
(fn [inner-done]
(ths/run-store
(ths/setup-store file) inner-done
[(dwl/set-file-shared (:id file) shared?)]
#(check % @calls)))
done))))
(t/deftest share-a-file-with-variants
(t/async
done
(let [file (-> (cthf/sample-file :file1)
(cthv/add-variant :v01 :c01 :m01 :c02 :m02))]
((share file true
(fn [state calls]
(t/is (true? (get-in state [:files (:id file) :is-shared])))
(t/is (= [[:set-file-shared {:id (:id file) :is-shared true}]] calls))))
done))))
(t/deftest unshare-a-file
(t/async
done
(let [file (cthf/sample-file :file1)]
((share file false
(fn [state calls]
(t/is (false? (get-in state [:files (:id file) :is-shared])))
(t/is (= [[:set-file-shared {:id (:id file) :is-shared false}]] calls))))
done))))

View File

@ -0,0 +1,203 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.data.workspace-library-updates-test
"How a file learns that a linked library changed and offers to sync: the
library change pushed by the server, the check of which libraries need a
sync, the sync dialog and its update and dismiss actions, and the sync
itself from an external library."
(:require
[app.common.test-helpers.components :as cthc]
[app.common.test-helpers.composable.core :as tm]
[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.common.types.file :as ctf]
[app.main.data.workspace.libraries :as dwl]
[app.main.repo :as rp]
[app.main.store :as st]
[cljs.test :as t :include-macros true]
[frontend-tests.composable-tests.interpreter :as ftm]
[frontend-tests.helpers.mock :as mock]
[potok.v2.core :as ptk]))
(t/use-fixtures :each ftm/fixture)
(def ^:private old-color "#111111")
(def ^:private new-color "#222222")
(def ^:private synced-at (js/Date. 1000))
(def ^:private component-changed-at (js/Date. 2000))
(def ^:private library-changed-at (js/Date. 3000))
(defn- library-and-file
"A library whose component :lib-c changed after the file last synced
with it, and a file with a copy of :lib-c. With `changed?`, the main
child got a fill after the copy was made, so a sync changes the copy."
[changed?]
(let [library (-> (cthf/sample-file :library :is-shared true)
(ctho/add-simple-component :lib-c :lib-main :lib-main-child
:child-params {:fills (cths/sample-fills-color
:fill-color old-color)})
;; `ctkl/update-component` would stamp the current date
(ctf/update-file-data
#(assoc-in % [:components (cthi/id :lib-c) :modified-at] component-changed-at))
(assoc :synced-at synced-at
:modified-at library-changed-at))
file (-> (cthf/sample-file :file1)
(cthc/instantiate-component :lib-c :copy
:library library
:children-labels [:copy-child])
(ctho/add-rect :rect))]
[(cond-> library
changed?
(cths/update-shape :lib-main-child :fills (cths/sample-fills-color :fill-color new-color)))
file]))
(defn- install-with-library!
[changed?]
(let [[library file] (library-and-file changed?)]
(ftm/install! (-> (tm/make-situation file)
(tm/with-aux-files {(:id library) library})))
library))
(defn- live-library
[]
(get-in @st/state [:files (cthi/id :library)]))
(defn- copy-fill
[]
(-> (cths/get-shape (ftm/current-file) :copy-child) :fills first :fill-color))
(defn- sleep
[ms]
(js/Promise. (fn [resolve] (js/setTimeout resolve ms))))
(defn- await-until
"Wait up to a second for `ready?`."
[ready?]
(ftm/await-step [] 1000 ready?))
(defn- notification
[]
(:notification @st/state))
(defn- rpc-commands
[]
(set (map :cmd @mock/rpc-calls)))
;; ----- Which libraries need a sync
(t/deftest assets-need-sync
(let [[library file] (library-and-file true)
data (:data file)]
(t/testing "a library changed after the last sync, with a used component changed too"
(t/is (= [{:shape-id (cthi/id :copy) :asset-id (cthi/id :lib-c)
:asset-type :component :container-id (cthf/current-page-id file)}]
(vec (dwl/assets-need-sync library data)))))
(t/testing "the file itself"
(t/is (nil? (dwl/assets-need-sync library (assoc data :id (:id library))))))
(t/testing "a library not changed since the last sync"
(t/is (nil? (dwl/assets-need-sync (assoc library :synced-at (js/Date. 4000)) data))))
(t/testing "changes before the date the user dismissed the updates"
(t/is (nil? (dwl/assets-need-sync library data (js/Date. 4000)))))
(t/testing "a used component that did not change"
(t/is (empty? (dwl/assets-need-sync (assoc library :synced-at (js/Date. 2500)) data))))))
;; ----- The sync dialog
(defn- sync-dialog-shown?
[]
(= :sync-dialog (:tag (notification))))
(t/deftest ^:async sync-dialog-updates-the-copies
(await
(mock/with-mocks*
{rp/cmd! mock/rpc-cmd-mock}
(install-with-library! true)
(t/is (= :settled (await (ftm/await-step [(dwl/notify-sync-file)] 1000 sync-dialog-shown?))))
((-> (notification) :accept :callback))
(await (await-until #(= new-color (copy-fill))))
(t/is (= new-color (copy-fill)))
(t/is (not= :visible (:status (notification))))
(t/is (not= synced-at (:synced-at (live-library))))
(t/is (contains? (rpc-commands) :update-file-library-sync-status)))))
(t/deftest ^:async sync-dialog-dismiss-ignores-the-changes
(await
(mock/with-mocks*
{rp/cmd! mock/rpc-cmd-mock}
(install-with-library! true)
(await (ftm/await-step [(dwl/notify-sync-file)] 1000 sync-dialog-shown?))
((-> (notification) :cancel :callback))
(t/is (some? (:ignore-sync-until (ftm/current-file))))
(t/is (contains? (rpc-commands) :ignore-file-library-sync-status))
(t/is (= old-color (copy-fill)))
(t/testing "no dialog for the same changes afterwards"
(st/emit! (dwl/notify-sync-file))
(await (sleep 50))
(t/is (not (sync-dialog-shown?)))))))
(t/deftest ^:async no-sync-dialog-when-the-sync-changes-nothing
(install-with-library! false)
(st/emit! (dwl/notify-sync-file))
(await (sleep 50))
(t/is (not (sync-dialog-shown?))))
(defn- view-only
[]
(ptk/reify ::view-only
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:permissions :can-edit] false))))
(t/deftest ^:async no-sync-dialog-without-edit-permission
(install-with-library! true)
(st/emit! (view-only) (dwl/notify-sync-file))
(await (sleep 50))
(t/is (not (sync-dialog-shown?))))
;; ----- Changes pushed by the server
(defn- rename-change
[library]
{:type :mod-obj
:page-id (cthf/current-page-id library)
:id (cthi/id :lib-main-child)
:operations [{:type :set :attr :name :val "Renamed"}]})
(t/deftest ^:async library-change-from-the-server
(await
(mock/with-mocks*
{dwl/fetch-library-thumbnails (mock/stub (fn [_] (ptk/data-event ::no-thumbnails)))}
(let [library (install-with-library! true)]
(await (ftm/await-step [(dwl/ext-library-changed (:id library) (js/Date. 5000) 7
[(rename-change library)])]))
(let [library' (live-library)]
(t/is (= 7 (:revn library')))
(t/is (= (js/Date. 5000) (:modified-at library')))
(t/is (= "Renamed" (:name (cths/get-shape library' :lib-main-child)))))))))
;; ----- Sync from an external library
(t/deftest ^:async sync-from-an-external-library
(await
(mock/with-mocks*
{rp/cmd! mock/rpc-cmd-mock}
(let [library (install-with-library! true)]
(await (ftm/await-step [(dwl/set-updating-library true)
(dwl/sync-file (:id (ftm/current-file)) (:id library))]))
(t/is (= new-color (copy-fill)))
(t/is (not (:updating-library @st/state)))
(t/is (not= synced-at (:synced-at (live-library))))
(t/is (contains? (rpc-commands) :update-file-library-sync-status))))))
(t/deftest ^:async set-updating-library
(await (ftm/await-step [(dwl/set-updating-library true)]))
(t/is (true? (:updating-library @st/state)))
(await (ftm/await-step [(dwl/set-updating-library false)]))
(t/is (nil? (:updating-library @st/state))))

View File

@ -10,53 +10,21 @@
component, or drop the commit. Plugin `waitForLayoutUpdate` and the
composable interpreter rely on it."
(:require
[app.common.files.changes-builder :as pcb]
[app.common.logic.shapes :as cls]
[app.common.test-helpers.composable.comp.setups :as setup]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[app.main.data.changes :as dch]
[app.main.data.workspace.reflow :as wrf]
[app.main.store :as st]
[app.plugins.reflow :as pwrf]
[cljs.test :as t :include-macros true]
[frontend-tests.composable-tests.interpreter :as ftm]))
;; The watcher schedules thumbnail renders that reach `window`, absent
;; headless (see `ftm/install-thumbnail-noop!`).
(t/use-fixtures :each
{:before (fn []
(thi/reset-idmap!)
(ftm/install-thumbnail-noop!))
:after ftm/restore-thumbnail!})
(t/use-fixtures :each ftm/fixture)
(def ^:private red "#ff0000")
(defn- main-child-fill-commit
"A commit that sets the main child's fill to red, with `opts` merged into the
commit params."
[opts]
(let [file (ftm/current-file)
page (thf/current-page file)
changes (cls/generate-update-shapes
(pcb/empty-changes nil (:id page))
#{(thi/id :main-child)}
#(assoc % :fills (ths/sample-fills-color :fill-color red))
(:objects page)
{})]
(dch/commit-changes (merge {:redo-changes (:redo-changes changes)
:undo-changes (:undo-changes changes)}
opts))))
(defn- sync-pending?
[file-id]
(contains? (get (wrf/pending) file-id) :sync-file))
(defn- fill-of
[label]
(-> (ths/get-shape (ftm/current-file) label) :fills first :fill-color))
(defn- run-commit
"Install a component with a copy and emit the main child fill commit with
`commit-opts`. Once the wait settles, call `check` with whether the sync
@ -65,7 +33,7 @@
[done commit-opts check]
(ftm/install! (setup/simple-component-with-labeled-copy))
(let [file-id (:id (ftm/current-file))]
(st/emit! (main-child-fill-commit commit-opts))
(st/emit! (ftm/fill-commit :main-child red commit-opts))
(let [open? (sync-pending? file-id)]
(-> (pwrf/wait-for-layout-update nil 2000)
(.then #(check open?)
@ -78,7 +46,7 @@
(run-commit done {}
(fn [open?]
(t/is open?)
(t/is (= red (fill-of :copy-child)))))))
(t/is (= red (ftm/fill-of :copy-child)))))))
(t/deftest undo-commit-holds-the-wait-until-the-watcher-handles-it
;; Undo and redo commit with `save-undo? false`. The watcher only touches

View File

@ -0,0 +1,75 @@
;; 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) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.data.workspace-undo-stack-test
"Tests undo and redo of an undo entry with no undo group. The entry schema
requires a group, but release builds elide the check, so a commit that
passes a nil `:undo-group` stores such an entry; undo and redo take a
branch of their own for it."
(:require
[app.common.files.changes-builder :as pcb]
[app.common.logic.shapes :as cls]
[app.common.test-helpers.composable.comp.setups :as setup]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[app.main.data.changes :as dch]
[app.main.data.workspace.undo :as dwu]
[app.main.store :as st]
[cljs.test :as t :include-macros true]
[frontend-tests.composable-tests.interpreter :as ftm]
[potok.v2.core :as ptk]))
(t/use-fixtures :each ftm/fixture)
(def ^:private red "#ff0000")
(defn- fill-main-child-changes
"The changes that fill the main child of the live file `color`."
[color]
(let [page (thf/current-page (ftm/current-file))]
(cls/generate-update-shapes (pcb/empty-changes nil (:id page))
#{(thi/id :main-child)}
#(assoc % :fills (ths/sample-fills-color :fill-color color))
(:objects page)
{})))
(defn- push-entry-without-group
"An event that adds `changes` to the undo stack as an entry with no undo
group, as a release build stores a commit whose `:undo-group` is nil."
[changes]
(ptk/reify ::push-entry-without-group
ptk/UpdateEvent
(update [_ state]
(update state :workspace-undo
(fn [undo]
(let [items (conj (vec (:items undo))
{:undo-changes (:undo-changes changes)
:redo-changes (:redo-changes changes)
:tags #{}})]
(assoc undo :items items :index (dec (count items)))))))))
(defn- undo-index
[]
(get-in @st/state [:workspace-undo :index]))
(t/deftest ^:async undo-and-redo-an-entry-without-undo-group
(ftm/install! (setup/simple-component-with-labeled-copy))
(let [changes (fill-main-child-changes red)]
(await (ftm/await-step [(dch/commit-changes {:redo-changes (:redo-changes changes)
:undo-changes (:undo-changes changes)
:save-undo? false})
(push-entry-without-group changes)]))
(t/is (= red (ftm/fill-of :main-child)))
(t/is (= 0 (undo-index)))
(t/is (= :settled (await (ftm/await-step [dwu/undo]))))
(t/is (= setup/labeled-fill (ftm/fill-of :main-child)))
(t/is (= -1 (undo-index)))
(t/is (= :settled (await (ftm/await-step [dwu/redo]))))
(t/is (= red (ftm/fill-of :main-child)))
(t/is (= 0 (undo-index)))))

View File

@ -5,34 +5,45 @@
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.data.workspace-variants-test
"The checks the workspace runs before combining components as variants
and before a variant switch, and the branches of the variant events that
the composable cases (`frontend-tests.composable-tests.comp.sync-test`)
do not reach: a combine on another page, a switch that would nest a
component in itself, the shortcuts with no variant selected and the
rename of a plain component."
(:require
[app.common.data :as d]
[app.common.files.changes-builder :as pcb]
[app.common.files.variant :as cfv]
[app.common.logic.variants :as clv]
[app.common.path-names :as cpn]
[app.common.test-helpers.components :as cthc]
[app.common.test-helpers.compositions :as tho]
[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.common.test-helpers.variants :as thv]
[app.common.test-helpers.variants :as cthv]
[app.common.types.component :as ctk]
[app.common.types.components-list :as ctkl]
[app.common.types.variant :as ctv]
[app.common.uuid :as uuid]
[app.main.data.common :as dcm]
[app.main.data.workspace :as dw]
[app.main.data.workspace.selection :as dws]
[app.main.data.workspace.undo :as dwu]
[app.main.data.workspace.variants :as dwv]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
[frontend-tests.helpers.mock :as mock]
[frontend-tests.helpers.state :as ths]
[potok.v2.core :as ptk]))
(t/use-fixtures :each
{:before cthi/reset-idmap!})
(t/use-fixtures :each {:before cthi/reset-idmap!})
(defn- two-property-file-on-other-page
[]
(-> (cthf/sample-file :file1 :page-label :page1)
(thv/add-variant-two-properties :v01 :c01 :m01 :c02 :m02)
(cthv/add-variant-two-properties :v01 :c01 :m01 :c02 :m02)
(cthf/add-sample-page :page2)))
(defn- run
@ -172,22 +183,22 @@
(defn- simple-main-file
[]
(-> (cthf/sample-file :file1)
(tho/add-simple-component :c01 :m01 :r01)))
(ctho/add-simple-component :c01 :m01 :r01)))
(defn- two-mains-file
[]
(-> (cthf/sample-file :file1)
(tho/add-simple-component :c01 :m01 :r01
(ctho/add-simple-component :c01 :m01 :r01
:root-params {:name "Alpha" :x 0 :y 0 :width 100 :height 80})
(tho/add-simple-component :c02 :m02 :r02
(ctho/add-simple-component :c02 :m02 :r02
:root-params {:name "Beta" :x 150 :y 0 :width 100 :height 80})))
(defn- two-mains-shared-prefix-file
[]
(-> (cthf/sample-file :file1)
(tho/add-simple-component :c01 :m01 :r01
(ctho/add-simple-component :c01 :m01 :r01
:root-params {:name "UI / Alpha" :x 0 :y 0 :width 100 :height 80})
(tho/add-simple-component :c02 :m02 :r02
(ctho/add-simple-component :c02 :m02 :r02
:root-params {:name "UI / Beta" :x 150 :y 0 :width 100 :height 80})))
(defn- three-same-name-mains-file
@ -203,16 +214,16 @@
(defn- path-named-main-file
[]
(-> (cthf/sample-file :file1)
(tho/add-simple-component :c01 :m01 :r01
(ctho/add-simple-component :c01 :m01 :r01
:root-params {:name "Group / Button"})))
(defn- two-mains-on-page1-with-page2
"Two mains on :page1; the open page is :page2 (Assets combine while elsewhere)."
[]
(-> (cthf/sample-file :file1 :page-label :page1)
(tho/add-simple-component :c01 :m01 :r01
(ctho/add-simple-component :c01 :m01 :r01
:root-params {:name "Alpha" :x 0 :y 0 :width 100 :height 80})
(tho/add-simple-component :c02 :m02 :r02
(ctho/add-simple-component :c02 :m02 :r02
:root-params {:name "Beta" :x 150 :y 0 :width 100 :height 80})
(cthf/add-sample-page :page2)
(cthf/switch-to-page :page2)))
@ -222,8 +233,8 @@
and before the container flag."
[]
(-> (cthf/sample-file :file1)
(tho/add-frame :v01 {:name "Set"})
(tho/add-simple-component :c01 :m01 :r01
(ctho/add-frame :v01 {:name "Set"})
(ctho/add-simple-component :c01 :m01 :r01
:root-params {:parent-label :v01 :name "Set"})))
(defn- component-full-name
@ -609,3 +620,176 @@
(t/is (= variant-id (:variant-id c01')))
(t/is (= variant-id (:variant-id c02')))))
after-commits-idle))))
(defn- setup-file
"A variant set (members :m01 and :m02, each with a child), a copy of :m01,
two plain components and a copy of the first."
[]
(-> (cthf/sample-file :file1)
(cthv/add-variant-with-child :v01 :c01 :m01 :c02 :m02 :m01-child :m02-child)
(cthc/instantiate-component :c01 :copy01 :children-labels [:copy01-child])
(ctho/add-simple-component :plain1 :plain1-root :plain1-child)
(ctho/add-simple-component :plain2 :plain2-root :plain2-child)
(cthc/instantiate-component :plain1 :plain1-copy)))
(defn- state-of
[file]
@(ths/setup-store file))
(t/deftest valid-components-for-variants
(let [file (setup-file)
state (state-of file)
page-id (:current-page-id state)
valid? #(dwv/valid-components-for-variants? state page-id (mapv cthi/id %))]
(t/testing "two plain main roots"
(t/is (valid? [:plain1-root :plain2-root])))
(t/testing "fewer than two distinct components"
(t/is (not (valid? [:plain1-root])))
(t/is (not (valid? [:plain1-root :plain1-root]))))
(t/testing "a variant main"
(t/is (not (valid? [:plain1-root :m01]))))
(t/testing "a copy"
(t/is (not (valid? [:plain1-root :plain1-copy]))))
(t/testing "a page that is not the current one"
(t/is (not (dwv/valid-components-for-variants?
state (uuid/next) [(cthi/id :plain1-root) (cthi/id :plain2-root)]))))))
(t/deftest valid-variant-switch
(let [file (setup-file)
state (state-of file)
valid? (fn [label pos val]
(dwv/valid-variant-switch? state (cths/get-shape file label) pos val))]
(t/testing "a variant copy head and a value some member holds"
(t/is (valid? :copy01 0 "Value2"))
(t/is (valid? :copy01 0 "Value1")))
(t/testing "a value no member holds"
(t/is (not (valid? :copy01 0 "Value3"))))
(t/testing "a position outside the properties"
(t/is (not (valid? :copy01 1 "Value2")))
(t/is (not (valid? :copy01 -1 "Value2"))))
(t/testing "a value that is not a string"
(t/is (not (valid? :copy01 0 2))))
(t/testing "not a variant copy head"
(t/is (not (valid? :m01 0 "Value2")))
(t/is (not (valid? :copy01-child 0 "Value2")))
(t/is (not (valid? :plain1-copy 0 "Value2"))))))
(defn- all-transactions-committed
"A `run-store` stopper: the first undo commit after which no transaction
is pending, for events that commit their transaction asynchronously."
[store]
(fn [stream]
(->> stream
(rx/filter (ptk/type? ::dwu/commit-undo-transaction))
(rx/filter #(empty? (get-in @store [:workspace-undo :transactions-pending]))))))
(defn- go-to-page
"Stands in for `dcm/go-to-workspace`, which needs the router: makes
`page-id` the current page and announces it as initialized."
[& {:keys [page-id]}]
(ptk/reify ::go-to-page
ptk/UpdateEvent
(update [_ state]
(assoc state :current-page-id page-id))
ptk/WatchEvent
(watch [_ _ _]
(rx/of (ptk/data-event :app.main.data.workspace.pages/initialize-page {})))))
(t/deftest combine-on-another-page
(t/async
done
(mock/with-mocks
{dcm/go-to-workspace go-to-page}
(fn [inner-done]
(let [file (cthf/sample-file :file1)
page-1 (cthf/current-page-id file)
file (-> file
(cthf/add-sample-page :page2)
(ctho/add-simple-component :plain1 :plain1-root :plain1-child)
(ctho/add-simple-component :plain2 :plain2-root :plain2-child)
(vary-meta assoc :current-page-id page-1))
store (ths/setup-store file)
ids [(cthi/id :plain1-root) (cthi/id :plain2-root)]]
(ths/run-store
store inner-done
[(dwv/combine-as-variants ids {:page-id (cthi/id :page2)
:trigger "plugin:combine-as-variants"})]
(fn [state]
(let [data (:data (ths/get-file-from-state state))
c1 (ctkl/get-component data (cthi/id :plain1))
c2 (ctkl/get-component data (cthi/id :plain2))]
(t/is (= (cthi/id :page2) (:current-page-id state)))
(t/is (some? (:variant-id c1)))
(t/is (= (:variant-id c1) (:variant-id c2)))))
(all-transactions-committed store))))
done)))
(t/deftest switch-into-a-nesting-loop
(t/async
done
(let [file (-> (cthf/sample-file :file1)
(cthv/add-variant :v01 :c01 :m01 :c02 :m02)
(cthc/instantiate-component :c01 :nested :parent-label :m02))
store (ths/setup-store file)
errors (atom 0)
params (with-meta {:shapes [(cths/get-shape file :nested)] :pos 0 :val "Value2"}
{:on-error #(swap! errors inc)})]
(ths/run-store
store done
[(dwv/variants-switch params)]
(fn [state]
(t/is (= 1 @errors))
(t/is (= (cthi/id :c01)
(:component-id (cths/get-shape (ths/get-file-from-state state) :nested)))))))))
(defn- object-count
[file]
(count (:objects (cthf/current-page file))))
(defn- run-selected
"Run `event` on a store for `file` with the shapes `labels` selected, then
`check` the resulting file."
[done file labels event check]
(ths/run-store
(ths/setup-store file) done
[(dws/select-shapes (into (d/ordered-set) (map cthi/id) labels)) event]
#(check (ths/get-file-from-state %))))
(defn- file-with-a-rect
[]
(-> (cthf/sample-file :file1)
(cths/add-sample-shape :rect)))
(t/deftest duplicate-shortcut-with-nothing-selected
(t/async
done
(let [file (file-with-a-rect)]
(run-selected done file [] (dwv/duplicate-or-add-variant)
#(t/is (= (object-count file) (object-count %)))))))
(t/deftest duplicate-shortcut-on-a-plain-shape
(t/async
done
(let [file (file-with-a-rect)]
(run-selected done file [:rect] (dwv/duplicate-or-add-variant)
#(t/is (= (inc (object-count file)) (object-count %)))))))
(t/deftest create-component-shortcut-on-a-plain-shape
(t/async
done
(run-selected done (file-with-a-rect) [:rect] (dwv/add-component-or-variant)
#(t/is (= 1 (count (ctkl/components-seq (:data %))))))))
(t/deftest rename-of-a-plain-component
(t/async
done
(let [file (-> (cthf/sample-file :file1)
(ctho/add-simple-component :plain1 :plain1-root :plain1-child))]
(ths/run-store
(ths/setup-store file) done
[(dwv/rename-comp-or-variant-and-main (cthi/id :plain1) "Renamed")]
(fn [state]
(let [file' (ths/get-file-from-state state)]
(t/is (= "Renamed" (:name (ctkl/get-component (:data file') (cthi/id :plain1)))))
(t/is (= "Renamed" (:name (cths/get-shape file' :plain1-root))))))))))

View File

@ -384,38 +384,37 @@
(t/is (= (count-shapes file' "rect-simple-1" "#333333") 2)))))))
done)))
;; FIXME: this test does not calls done consistently, so it break all the test suite
#_(t/deftest copy-nested-3
(t/async done
(mock/with-mocks {uuid/next cthi/next-uuid}
(fn [done']
(let [;; ==== Setup
file (setup-file)
store (ths/setup-store file)
(t/deftest copy-nested-3
(t/async done
(mock/with-mocks {uuid/next cthi/next-uuid}
(fn [done']
(let [;; ==== Setup
file (setup-file)
store (ths/setup-store file)
;; ==== Action
;; For each copy of Simple1 nested in a main or other copy, and the group inside Composed3
;; main and copy:
;; - Duplicate it two times, moving the duplicates to another page
events
(concat
(duplicate-copy-nested-and-group-out-of-the-main file :target-page-label :page-2)
;; - Change color of Simple1
(set-color-bottom-shape :frame-simple-1 file {:color "#111111"})
;; - Change color of the previous main
(set-color-bottom-shape :frame-composed-1 file {:color "#222222"})
(set-color-bottom-shape :group-3 file {:color "#333333"}))]
`(ths/run-store
store done' events
(fn [new-state]
(let [file' (-> (ths/get-file-from-state new-state)
(cthf/switch-to-page :page-2))]
(cthf/validate-file! file')
;; Check that it's NOT PROPAGATED.
(t/is (= (count-shapes file' "rect-simple-1" "#111111") 10))
(t/is (= (count-shapes file' "rect-simple-1" "#222222") 4))
(t/is (= (count-shapes file' "rect-simple-1" "#333333") 0)))))))
done)))
;; ==== Action
;; For each copy of Simple1 nested in a main or other copy, and the group inside Composed3
;; main and copy:
;; - Duplicate it two times, moving the duplicates to another page
events
(concat
(duplicate-copy-nested-and-group-out-of-the-main file :target-page-label :page-2)
;; - Change color of Simple1
(set-color-bottom-shape :frame-simple-1 file {:color "#111111"})
;; - Change color of the previous main
(set-color-bottom-shape :frame-composed-1 file {:color "#222222"})
(set-color-bottom-shape :group-3 file {:color "#333333"}))]
(ths/run-store
store done' events
(fn [new-state]
(let [file' (-> (ths/get-file-from-state new-state)
(cthf/switch-to-page :page-2))]
(cthf/validate-file! file')
;; Check that it's NOT PROPAGATED.
(t/is (= (count-shapes file' "rect-simple-1" "#111111") 10))
(t/is (= (count-shapes file' "rect-simple-1" "#222222") 4))
(t/is (= (count-shapes file' "rect-simple-1" "#333333") 0)))))))
done)))
(t/deftest duplicate-page-integrity-frame-group-component
;; This test covers the bug fixed in 2.9.0: duplicating a page with a mainInstance inside a group

View File

@ -8,8 +8,10 @@
[frontend-tests.browser-history-test]
[frontend-tests.code-gen-style-test]
[frontend-tests.composable-tests.comp.sync-test]
[frontend-tests.composable-tests.completion-contract-test]
[frontend-tests.copy-as-svg-test]
[frontend-tests.data.auth-test]
[frontend-tests.data.changes-test]
[frontend-tests.data.comments-batches-test]
[frontend-tests.data.comments-filters-test]
[frontend-tests.data.dashboard-test]
@ -37,9 +39,13 @@
[frontend-tests.data.workspace-colors-test]
[frontend-tests.data.workspace-comments-test]
[frontend-tests.data.workspace-context-menu-test]
[frontend-tests.data.workspace-edit-watchers-test]
[frontend-tests.data.workspace-focus-test]
[frontend-tests.data.workspace-interactions-test]
[frontend-tests.data.workspace-libraries-sync-test]
[frontend-tests.data.workspace-libraries-test]
[frontend-tests.data.workspace-library-links-test]
[frontend-tests.data.workspace-library-updates-test]
[frontend-tests.data.workspace-mcp-test]
[frontend-tests.data.workspace-media-test]
[frontend-tests.data.workspace-notifications-test]
@ -50,9 +56,11 @@
[frontend-tests.data.workspace-sync-barrier-test]
[frontend-tests.data.workspace-texts-test]
[frontend-tests.data.workspace-thumbnails-test]
[frontend-tests.data.workspace-undo-stack-test]
[frontend-tests.data.workspace-undo-test]
[frontend-tests.data.workspace-undo-translation-test]
[frontend-tests.data.workspace-variant-rename-test]
[frontend-tests.data.workspace-variant-switch-wasm-test]
[frontend-tests.data.workspace-variants-test]
[frontend-tests.data.workspace-versions-test]
[frontend-tests.debug-logging-test]
@ -209,8 +217,10 @@
['frontend-tests.basic-shapes-test
'frontend-tests.code-gen-style-test
'frontend-tests.composable-tests.comp.sync-test
'frontend-tests.composable-tests.completion-contract-test
'frontend-tests.copy-as-svg-test
'frontend-tests.data.auth-test
'frontend-tests.data.changes-test
'frontend-tests.data.comments-batches-test
'frontend-tests.data.comments-filters-test
'frontend-tests.data.dashboard-test
@ -242,22 +252,28 @@
'frontend-tests.data.workspace-colors-test
'frontend-tests.data.workspace-comments-test
'frontend-tests.data.workspace-context-menu-test
'frontend-tests.data.workspace-edit-watchers-test
'frontend-tests.data.workspace-focus-test
'frontend-tests.data.workspace-interactions-test
'frontend-tests.data.workspace-libraries-sync-test
'frontend-tests.data.workspace-libraries-test
'frontend-tests.data.workspace-library-links-test
'frontend-tests.data.workspace-library-updates-test
'frontend-tests.data.workspace-mcp-test
'frontend-tests.data.workspace-media-test
'frontend-tests.data.workspace-notifications-test
'frontend-tests.data.workspace-pages-test
'frontend-tests.data.workspace-path-edition-test
'frontend-tests.data.workspace-reflow-test
'frontend-tests.data.workspace-sync-barrier-test
'frontend-tests.data.workspace-shortcuts-test
'frontend-tests.data.workspace-sync-barrier-test
'frontend-tests.data.workspace-texts-test
'frontend-tests.data.workspace-thumbnails-test
'frontend-tests.data.workspace-undo-stack-test
'frontend-tests.data.workspace-undo-test
'frontend-tests.data.workspace-undo-translation-test
'frontend-tests.data.workspace-variant-rename-test
'frontend-tests.data.workspace-variant-switch-wasm-test
'frontend-tests.data.workspace-variants-test
'frontend-tests.data.workspace-versions-test
'frontend-tests.debug-logging-test

View File

@ -6,6 +6,9 @@ import { createTestCaseVariantSwitchPropagates } from "./cases/caseVariantSwitch
import { createTestCaseCopySubheadDeletePreservesSlots } from "./cases/caseCopySubheadDeletePreservesSlots.ts";
import { createTestCaseMainReorderKeepsCopySlots } from "./cases/caseMainReorderKeepsCopySlots.ts";
import { createTestCaseMainChildMovedOutLeavesCopy } from "./cases/caseMainChildMovedOutLeavesCopy.ts";
import { createTestCaseDetachKeepsNestedCopiesLinked } from "./cases/caseDetachKeepsNestedCopiesLinked.ts";
import { createTestCaseCopySwapSurvivesMainChanges } from "./cases/caseCopySwapSurvivesMainChanges.ts";
import { createTestCaseResetOfNestedSwapKeepsTopCopyOverrides } from "./cases/caseResetOfNestedSwapKeepsTopCopyOverrides.ts";
/**
* All composable test cases currently defined. A factory (not a constant): each
@ -21,5 +24,8 @@ export function allCases(): readonly TestCase[] {
createTestCaseCopySubheadDeletePreservesSlots(),
createTestCaseMainReorderKeepsCopySlots(),
createTestCaseMainChildMovedOutLeavesCopy(),
createTestCaseDetachKeepsNestedCopiesLinked(),
createTestCaseCopySwapSurvivesMainChanges(),
createTestCaseResetOfNestedSwapKeepsTopCopyOverrides(),
];
}

View File

@ -0,0 +1,84 @@
import { TestCase } from "../test-suite/TestCase.ts";
import { Situation } from "../core/Situation";
import { Color } from "../model/Color";
import { ShapePropFillColor } from "../model/ShapeProp.ts";
import { OpChangeProperty } from "../operations/OpChangeProperty";
import { OpAssert } from "../operations/OpAssert";
import { OpCreateNestableComponent } from "../operations/OpCreateNestableComponent";
import { ContentCreationStrategyRectangle } from "../content-creation/ContentCreationStrategyRectangle.ts";
import { OpSequence } from "../operations/OpSequence.ts";
import { OpOptional } from "../operations/OpOptional.ts";
import { OpSwap } from "../operations/OpSwap.ts";
import { Assert } from "../util/Assert.ts";
// distinct fill colours (read-back values are lower-case)
const BASELINE = new Color("#aaaaaa");
const RED = new Color("#ff0000"); // the component the copy swaps to
const GREEN = new Color("#00ff00"); // the component the main swaps to
const BLUE = new Color("#0000ff"); // remote edit
/**
* Case AA — a copy's swap survives changes to the main.
*
* A component nests a copy of another; a copy of the outer component swaps its
* nested copy for a third component. Optionally the outer main then swaps its own
* nested copy for a fourth component, and optionally the nested component's main
* changes its rect. The copy's nested head stays an instance of the component it
* swapped to, showing that component's rect.
*/
export function createTestCaseCopySwapSurvivesMainChanges(): TestCase {
const opCreateComponent = new OpCreateNestableComponent(new ContentCreationStrategyRectangle(BASELINE));
const opCreateRed = new OpCreateNestableComponent(new ContentCreationStrategyRectangle(RED), "red");
const opCreateGreen = new OpCreateNestableComponent(new ContentCreationStrategyRectangle(GREEN), "green");
const fillColor = new ShapePropFillColor();
const { remoteInstance } = opCreateComponent.roles;
// the nested copy inside the outer copy, and inside the outer main
const copyNested = (s: Situation) => opCreateComponent.getNestedInstance(s, 1);
const mainNested = (s: Situation) => opCreateComponent.getCopyInstance(s, 0);
return new TestCase(
"CopySwapSurvivesMainChanges",
"A component containing a rectangle is created and nested once in an outer component, " +
"and two more components with differently coloured rectangles are created. A copy " +
"of the outer component swaps its nested copy for the first of them. Optionally the " +
"outer main swaps its own nested copy for the second, and optionally the nested " +
"component's main recolours its rectangle. The copy's swap must survive: its nested " +
"copy stays an instance of the component it swapped to and shows its colour.",
new OpSequence(
opCreateComponent,
opCreateRed,
opCreateGreen,
opCreateComponent.createOpInstantiate(),
opCreateComponent.createOpMakeNested(),
new OpSwap(
copyNested,
(s) => opCreateRed.getMainComponent(s),
"the copy's nested copy for the red component"
),
new OpOptional(
new OpSwap(
mainNested,
(s) => opCreateGreen.getMainComponent(s),
"the main's nested copy for the green component"
)
),
new OpOptional(
new OpChangeProperty(
(s: Situation) => opCreateComponent.contentCreator.getRectangle(s.get(remoteInstance)),
fillColor,
BLUE,
"remote rect"
)
),
new OpAssert("the copy's nested copy keeps its swap", (s) => {
const head = copyNested(s);
Assert.that(
head.component()?.id === opCreateRed.getMainComponent(s).id,
"the nested copy is a red instance"
);
fillColor.assertEqual(fillColor.read(opCreateComponent.contentCreator.getRectangle(head)), RED);
})
)
);
}

View File

@ -0,0 +1,73 @@
import { Shape } from "@penpot/plugin-types";
import { TestCase } from "../test-suite/TestCase.ts";
import { Situation } from "../core/Situation";
import { Color } from "../model/Color";
import { ShapePropFillColor } from "../model/ShapeProp.ts";
import { OpChangeProperty } from "../operations/OpChangeProperty";
import { OpAssert } from "../operations/OpAssert";
import { OpCreateNestableComponent } from "../operations/OpCreateNestableComponent";
import { ContentCreationStrategyRectangle } from "../content-creation/ContentCreationStrategyRectangle.ts";
import { OpSequence } from "../operations/OpSequence.ts";
import { OpOptional } from "../operations/OpOptional.ts";
import { OpDetach } from "../operations/OpDetach.ts";
import { Assert } from "../util/Assert.ts";
// distinct fill colours (read-back values are lower-case)
const BASELINE = new Color("#aaaaaa");
const GREEN = new Color("#00ff00"); // main edit
const BLUE = new Color("#0000ff"); // remote edit
/**
* Case Q — a detached copy's nested copies stay linked.
*
* At nesting depth 0, 1 or 2, optionally change the main's rect, detach the
* copy, then change the remote (original) main's rect. At depth 0 the copy's
* rect is detached and keeps its value. Deeper, the rect lies in a nested copy,
* which stays a copy one level up and inherits the main's override: with it the
* rect keeps the main's colour, without it the rect follows the remote main.
*/
export function createTestCaseDetachKeepsNestedCopiesLinked(): TestCase {
const opCreateComponent = new OpCreateNestableComponent(new ContentCreationStrategyRectangle(BASELINE));
const fillColor = new ShapePropFillColor();
const { remoteInstance, mainInstance, copyInstance } = opCreateComponent.roles;
const rectOf =
(role: typeof remoteInstance) =>
(s: Situation): Shape =>
opCreateComponent.contentCreator.getRectangle(s.get(role));
const nestings = [opCreateComponent.createOpMakeNested(), opCreateComponent.createOpMakeNested()];
const changeMain = new OpChangeProperty(rectOf(mainInstance), fillColor, GREEN, "main rect");
const changeRemote = new OpChangeProperty(rectOf(remoteInstance), fillColor, BLUE, "remote rect");
return new TestCase(
"DetachKeepsNestedCopiesLinked",
"A component containing a rectangle is created and a copy is instantiated from it, " +
"optionally nested one or two levels deep. Optionally the current main's rectangle " +
"is coloured. The copy is then detached, and the originally created (remote) main's " +
"rectangle is coloured. Without nesting the copy's rectangle is no longer linked and " +
"keeps its colour. With nesting it lies in a nested copy that stays linked: it keeps " +
"the main's colour when the main was coloured, and otherwise follows the remote main.",
new OpSequence(
opCreateComponent,
opCreateComponent.createOpInstantiate(),
new OpOptional(nestings[0]),
new OpOptional(nestings[1]),
new OpOptional(changeMain),
new OpDetach(copyInstance, "copy"),
changeRemote,
new OpAssert("the copy's rect follows the rule for its depth", (s) => {
const rect = rectOf(copyInstance)(s);
const nested = nestings.some((n) => s.wasApplied(n));
const main = s.wasApplied(changeMain);
if (nested) {
Assert.that(rect.isComponentInstance(), "the nested rect stays linked");
fillColor.assertEqual(fillColor.read(rect), main ? GREEN : BLUE);
} else {
Assert.that(!rect.isComponentInstance(), "the detached rect is not linked");
fillColor.assertEqual(fillColor.read(rect), main ? GREEN : BASELINE);
}
})
)
);
}

View File

@ -9,6 +9,7 @@ import { OpCreateNestableComponent } from "../operations/OpCreateNestableCompone
import { ContentCreationStrategyRectangle } from "../content-creation/ContentCreationStrategyRectangle.ts";
import { OpSequence } from "../operations/OpSequence.ts";
import { OpOptional } from "../operations/OpOptional.ts";
import { OpReset } from "../operations/OpReset.ts";
// distinct fill colours (read-back values are lower-case)
const BASELINE = new Color("#aaaaaa");
@ -28,8 +29,8 @@ const BLUE = new Color("#0000ff"); // copy edit
* tracked instance roles' rects (resolved via the strategy at the current depth),
* so the same composition holds at any depth.
*
* (The reset checkpoint of the original case is omitted: the Plugin API exposes no
* override-reset operation.)
* Then a copy override is forced and reset away: after the reset the copy shows
* the main change, else the remote change, else the baseline.
*/
export function createTestCaseRemoteMainCopySyncNested(): TestCase {
const opCreateComponent = new OpCreateNestableComponent(new ContentCreationStrategyRectangle(BASELINE));
@ -45,6 +46,7 @@ export function createTestCaseRemoteMainCopySyncNested(): TestCase {
const changeRemote = new OpChangeProperty(rectOf(remoteInstance), fillColor, RED, "remote rect");
const changeMain = new OpChangeProperty(rectOf(mainInstance), fillColor, GREEN, "main rect");
const changeCopy = new OpChangeProperty(rectOf(copyInstance), fillColor, BLUE, "copy rect");
const forceCopy = new OpChangeProperty(rectOf(copyInstance), fillColor, BLUE, "copy rect");
// the colour expected at the copy under the precedence rule
const expectedAtCopy = (s: Situation): Color => {
@ -63,7 +65,9 @@ export function createTestCaseRemoteMainCopySyncNested(): TestCase {
"then applied: colouring the rectangle on the remote, on the current main, and on the " +
"copy. The copy's rectangle must show the highest-precedence applied edit — a copy " +
"override wins over a main change, which wins over a remote change, which wins over " +
"the baseline — at every nesting depth.",
"the baseline — at every nesting depth. Finally the copy's rectangle is overridden " +
"once more and the copy's overrides are reset: it then shows the main change, else " +
"the remote change, else the baseline.",
new OpSequence(
opCreateComponent,
opCreateComponent.createOpInstantiate(),
@ -77,6 +81,14 @@ export function createTestCaseRemoteMainCopySyncNested(): TestCase {
new OpAssert("scopy shows the highest-precedence applied edit", (s) => {
const copyRect = opCreateComponent.contentCreator.getRectangle(s.get(copyInstance));
fillColor.assertEqual(fillColor.read(copyRect), expectedAtCopy(s));
}),
// force a copy override, then reset it away
forceCopy,
new OpReset(copyInstance),
new OpAssert("after the reset the copy shows the main's value", (s) => {
const copyRect = opCreateComponent.contentCreator.getRectangle(s.get(copyInstance));
const expected = s.wasApplied(changeMain) ? GREEN : s.wasApplied(changeRemote) ? RED : BASELINE;
fillColor.assertEqual(fillColor.read(copyRect), expected);
})
)
);

View File

@ -0,0 +1,68 @@
import { TestCase } from "../test-suite/TestCase.ts";
import { Situation } from "../core/Situation";
import { Color } from "../model/Color";
import { ShapePropFillColor, ShapePropOpacity } from "../model/ShapeProp.ts";
import { OpChangeProperty } from "../operations/OpChangeProperty";
import { OpAssert } from "../operations/OpAssert";
import { OpCreateNestableComponent } from "../operations/OpCreateNestableComponent";
import { ContentCreationStrategyRectangle } from "../content-creation/ContentCreationStrategyRectangle.ts";
import { OpSequence } from "../operations/OpSequence.ts";
import { OpSwap } from "../operations/OpSwap.ts";
import { OpReset } from "../operations/OpReset.ts";
import { Assert } from "../util/Assert.ts";
// distinct fill colours (read-back values are lower-case)
const BASELINE = new Color("#aaaaaa");
const RED = new Color("#ff0000"); // the component the copy swaps to
/**
* Case AB — resetting a nested swap leaves the rest of the top copy alone.
*
* A copy of a component that nests another overrides its own root's opacity,
* swaps its nested copy for a third component, then resets the nested copy. The
* reset undoes the swap and must change nothing outside the nested copy. It also
* clears the root's opacity override (F12 in the stabilization plan), pinned as a
* known failure.
*/
export function createTestCaseResetOfNestedSwapKeepsTopCopyOverrides(): TestCase {
const opCreateComponent = new OpCreateNestableComponent(new ContentCreationStrategyRectangle(BASELINE));
const opCreateRed = new OpCreateNestableComponent(new ContentCreationStrategyRectangle(RED), "red");
const fillColor = new ShapePropFillColor();
const opacity = new ShapePropOpacity();
const { copyInstance } = opCreateComponent.roles;
const copyNested = (s: Situation) => opCreateComponent.getNestedInstance(s, 1);
const redComponent = (s: Situation) => opCreateRed.getMainComponent(s);
return new TestCase(
"ResetOfNestedSwapKeepsTopCopyOverrides",
"A component containing a rectangle is created and nested once in an outer component; " +
"another component with a red rectangle is created. A copy of the outer component " +
"lowers its own opacity, swaps its nested copy for the red component, and then resets " +
"the nested copy. The reset must undo the swap (the nested copy shows the original " +
"rectangle again) and leave the copy's own opacity override alone. The reset also " +
"clears that override (known failure F12).",
new OpSequence(
opCreateComponent,
opCreateRed,
opCreateComponent.createOpInstantiate(),
opCreateComponent.createOpMakeNested(),
new OpChangeProperty(copyInstance, opacity, 0.5, "copy"),
new OpSwap(copyNested, redComponent, "the copy's nested copy for the red component"),
new OpReset(copyNested, "the copy's nested copy"),
new OpAssert("the reset undoes the swap and keeps the copy's opacity", (s) => {
const head = copyNested(s);
Assert.that(head.component()?.id !== redComponent(s).id, "the nested copy is no longer red");
fillColor.assertEqual(fillColor.read(opCreateComponent.contentCreator.getRectangle(head)), BASELINE);
// the reset clears the opacity, which the API then reads as null
Assert.knownFailure<number | null>(
"F12",
0.5,
null,
opacity.read(s.get(copyInstance)) ?? null,
(a, b) => a === b
);
})
)
);
}

View File

@ -137,3 +137,16 @@ export class ShapePropHeight extends ShapePropNumberBase {
shape.resize(shape.width, value);
}
}
/** The opacity of a shape, from 0 to 1. Reads and writes `opacity` directly. */
export class ShapePropOpacity extends ShapePropNumberBase {
readonly name = "opacity";
read(shape: Shape): number {
return shape.opacity;
}
write(shape: Shape, value: number): void {
shape.opacity = value;
}
}

View File

@ -1,4 +1,4 @@
import { Board, Shape } from "@penpot/plugin-types";
import { Board, LibraryComponent, Shape } from "@penpot/plugin-types";
import { Situation } from "../core/Situation";
import { Operation } from "../core/Operation";
import { Role } from "../core/Role";
@ -26,9 +26,20 @@ const NESTED_COMPONENT_NAME = "OuterComponentRoot";
* given instance via the content-creation strategy.
*/
class RolesNestableComponent extends RoleBundle {
readonly remoteInstance = new Role<Board>("remote-instance");
readonly mainInstance = new Role<Board>("main-instance");
readonly copyInstance = new Role<Board>("copy-instance");
readonly remoteInstance: Role<Board>;
readonly mainInstance: Role<Board>;
readonly copyInstance: Role<Board>;
/**
* @param prefix - prepended to the role names, so several lineages can be
* bound in one situation (roles are bound by name)
*/
constructor(prefix: string) {
super();
this.remoteInstance = new Role<Board>(`${prefix}remote-instance`);
this.mainInstance = new Role<Board>(`${prefix}main-instance`);
this.copyInstance = new Role<Board>(`${prefix}copy-instance`);
}
}
/**
@ -131,16 +142,22 @@ class OpMakeNestedComponent extends Operation {
* (e.g. as the target of a variant switch) without knowing how nesting is stored.
*/
export class OpCreateNestableComponent<TContentCreator extends ContentCreationStrategy> extends Operation {
readonly roles = new RolesNestableComponent();
readonly roles: RolesNestableComponent;
/** Private key under which this lineage's (mutable) nesting data is stored. */
private readonly nestingDataKey = new DataKey<NestingData>("nesting-data");
/**
* @param contentCreator - creates and locates the component's content
* @param name - names the lineage when a situation holds more than one; its
* roles are bound under names prefixed with it
*/
constructor(public readonly contentCreator: TContentCreator) {
constructor(
public readonly contentCreator: TContentCreator,
name: string = ""
) {
super();
this.roles = new RolesNestableComponent(name === "" ? "" : `${name}-`);
}
async applyTo(situation: Situation): Promise<void> {
@ -227,4 +244,16 @@ export class OpCreateNestableComponent<TContentCreator extends ContentCreationSt
}
return copy;
}
/**
* @param situation - the situation
* @return the component of the current main instance (the outermost one once nested)
*/
getMainComponent(situation: Situation): LibraryComponent {
const component = situation.get(this.roles.mainInstance).component();
if (component === null) {
throw new Error("the main instance has no component");
}
return component;
}
}

View File

@ -0,0 +1,34 @@
import { Operation } from "../core/Operation";
import { Situation } from "../core/Situation";
import { ShapeTarget, resolveTarget } from "../core/ShapeTarget";
import { PenpotSync } from "../util/PenpotSync";
/**
* Detaches the copy head a target resolves to from its component, via the
* Plugin API's `detach()`. The copy's shapes lose their component links; its
* nested copies stay copies, one nesting level up.
*/
export class OpDetach extends Operation {
/**
* @param target - resolves the copy head to detach
* @param targetLabel - a human-readable name for the detached shape, used in
* the applied-operation log; defaults to the target's own string form
*/
constructor(
private readonly target: ShapeTarget,
private readonly targetLabel: string = String(target)
) {
super();
}
async applyTo(situation: Situation): Promise<void> {
// act on the settled document, as a user would
await PenpotSync.awaitPropagation();
resolveTarget(this.target, situation).detach();
await PenpotSync.awaitPropagation();
}
toString(): string {
return `detach ${this.targetLabel}`;
}
}

View File

@ -0,0 +1,36 @@
import { Shape } from "@penpot/plugin-types";
import { Operation } from "../core/Operation";
import { Situation } from "../core/Situation";
import { ShapeTarget, resolveTarget } from "../core/ShapeTarget";
import { PenpotSync } from "../util/PenpotSync";
/**
* Resets the overrides of the copy head a target resolves to, via the Plugin
* API's `resetOverrides()`: its subtree becomes equal to its main again.
*/
export class OpReset extends Operation {
/**
* @param target - resolves the copy head to reset
* @param targetLabel - a human-readable name for the reset shape, used in
* the applied-operation log; defaults to the target's own string form
*/
constructor(
private readonly target: ShapeTarget,
private readonly targetLabel: string = String(target)
) {
super();
}
async applyTo(situation: Situation): Promise<void> {
// act on the settled document, as a user would
await PenpotSync.awaitPropagation();
// the published @penpot/plugin-types the suite pins predates `resetOverrides`
const shape = resolveTarget(this.target, situation) as Shape & { resetOverrides(): void };
shape.resetOverrides();
await PenpotSync.awaitPropagation();
}
toString(): string {
return `reset overrides of ${this.targetLabel}`;
}
}

View File

@ -0,0 +1,40 @@
import { LibraryComponent } from "@penpot/plugin-types";
import { Operation } from "../core/Operation";
import { Situation } from "../core/Situation";
import { ShapeTarget, resolveTarget } from "../core/ShapeTarget";
import { PenpotSync } from "../util/PenpotSync";
/**
* Swaps the copy head a target resolves to for an instance of another
* component, via the Plugin API's `swapComponent()`. The new head keeps the
* old head's id, so a target that found the old head finds the new one.
*
* Unlike the swap in the workspace UI, the API keeps the head's overrides
* (it swaps with keep-touched, F33 in the stabilization plan).
*/
export class OpSwap extends Operation {
/**
* @param target - resolves the copy head to swap
* @param component - resolves the component to swap to
* @param label - a human-readable description of the swap, used in the
* applied-operation log
*/
constructor(
private readonly target: ShapeTarget,
private readonly component: (situation: Situation) => LibraryComponent,
private readonly label: string
) {
super();
}
async applyTo(situation: Situation): Promise<void> {
// act on the settled document, as a user would
await PenpotSync.awaitPropagation();
resolveTarget(this.target, situation).swapComponent(this.component(situation));
await PenpotSync.awaitPropagation();
}
toString(): string {
return `swap ${this.label}`;
}
}

View File

@ -30,4 +30,28 @@ export class Assert {
throw new AssertionError(`expected ${render(expected)} but was ${render(actual)}`);
}
}
/**
* Asserts a strict expected failure for `bug` (its row in the component
* stabilization plan's suspected bugs): `expected` is the value that should
* hold, but while the bug is open `actual` must be exactly `pinned`, the
* wrong value the bug gives. Any other value fails, `expected` included, so
* the pin goes only with the fix.
*/
static knownFailure<T>(
bug: string,
expected: T,
pinned: T,
actual: T,
equals: (a: T, b: T) => boolean,
render: (v: T) => string = String
): void {
if (!equals(actual, pinned)) {
const fixed = equals(actual, expected) ? ". The expected value now holds: drop the pin in the fix" : "";
throw new AssertionError(
`known failure ${bug}: expected ${render(expected)}, pinned to the bug's ` +
`${render(pinned)}, but was ${render(actual)}${fixed}`
);
}
}
}