📚 Consolidate component and integrity guidance

Bring component and variant behavior, referential repair, and diagnosis
together while keeping schema validation and change mechanics separate.

AI-assisted-by: gpt-6.1-terra
This commit is contained in:
Andrey Antukh 2026-11-24 09:11:18 +00:00
parent c405a08334
commit 5e45bdb570
11 changed files with 58 additions and 135 deletions

View File

@ -1,8 +1,7 @@
# Common change application
- Start at `app.common.files.changes` and the shape-tree helpers. `process-changes` validates the change vector once by default, reduces it and then processes collected touched changes; `verify? false` is for callers that already validated. A touched shape in a main instance can mark its component modified in the second pass.
- `:set` delegates to `ctn/set-shape-attr`; `:assign` decodes attrs before applying per-attr sets. `:position-data` is derived and never touched. Geometry and content-path comparisons use approximate equality for touched purposes, but width and height are excluded from the `is-geometry?` branch.
- `:mov-objects` and `:reorder-children` protect children inside component copies unless `allow-altering-copies` is set by a sync or swap flow. New structural change types must preserve that boundary.
- `cls/generate-delete-shapes` propagates deletion from inside a component main to referencing copies transitively across the file, preventing dangling `shape-ref`s. It skips this when deleting the main root itself or when `allow-altering-copies` is set.
- `shape-tree/add-shape` falls back invalid parents or frames to root, keeps parent `:shapes` a vector without duplicate IDs, and clears a copy parent's `:remote-synced` unless `ignore-touched`. `delete-shape` removes descendants from the objects map as well as unlinking the parent; render-wasm deletion has different undo internals.
- Page-object maps can carry metadata indexes. Rebuild them with `start-page-index` / `update-page-index` as appropriate; frontend commit application calls `ctst/update-object-indices` after page changes. For change construction and undo see `mem:common/changes-architecture`; for validation and repair see `mem:common/file-validation`.
- Start at `app.common.files.changes` and the shape-tree helpers. `process-changes` validates the change vector once by default, reduces it and then processes collected touched changes; `verify? false` is for callers that already validated. Component-specific touched and copy rules are in `mem:common/components`.
- `:set` delegates to `ctn/set-shape-attr`; `:assign` decodes attrs before applying per-attr sets.
- `shape-tree/add-shape` falls back invalid parents or frames to root and keeps parent `:shapes` a vector without duplicate IDs. `delete-shape` removes descendants from the objects map as well as unlinking the parent; render-wasm deletion has different undo internals.
- Page-object maps can carry metadata indexes. Rebuild them with `start-page-index` / `update-page-index` as appropriate; frontend commit application calls `ctst/update-object-indices` after page changes. For change construction and undo see `mem:common/changes-architecture`.
- `update-file` also uses change-scoped schema validation: `touched-page-ids` selects pages while non-page data is checked whole. Register new change types as page-writing or file-level; unknown types fall back to the full schema check, which loads every page.

View File

@ -4,4 +4,4 @@
- Compaction must preserve redo and undo order: merge `:reg-objects` per container and put the registrations after the changes that resize the children. Never compact across commit boundaries; the backend can reject individual commits by `commit-id`. See `mem:frontend/workspace-state-persistence-subtleties` for the save order.
- Don't send a deleted component's entire object map with a metadata-only edit. Scope shape edits to `:component-id` using the builder's container context. In component metadata, omitted `:objects` preserves stored shapes; explicit nil clears them. Reserve `:objects? true` for repairs that intentionally move or clear the whole map.
- Apply fixture edits through `app.common.test-helpers.files/apply-changes` so tests exercise the production applier. Disable fixture validation only for intentionally invalid intermediate states. See `mem:common/testing`.
- For touched groups see `mem:common/component-data-model`; for the second pass see `mem:common/change-application` and for validation see `mem:common/file-validation`. For live inspection of emitted changes, see `mem:common/component-debugging-recipes`.
- For components, touched groups, referential integrity and live diagnosis see `mem:common/components`; for change application and schema validation see `mem:common/change-application`.

View File

@ -1,47 +0,0 @@
# Component and Variant Data Model
## Shape roles relative to components
A shape can occupy multiple roles at once:
1. Master/main instance: defines a component and has `:main-instance true` plus `:component-id`.
2. Copy/non-main instance: produced by instantiating a component and carries `:shape-ref` pointing at the master shape. `(ctk/in-component-copy? shape)` is essentially `(some? (:shape-ref shape))`.
3. Component root: topmost shape of an instance, marked `:component-root true` and carrying surface attrs such as `:component-id` and `:component-file`.
Variant masters are main instances and component roots. Their descendants may themselves be component copies, so master/copy logic must handle nested instances rather than assuming those roles are exclusive.
## :shape-ref chains
`:shape-ref` walks up the inheritance hierarchy and can cross files for remote libraries. `find-ref-shape` and `get-ref-chain-until-target-ref` in `app.common.types.file` follow this chain.
`find-shape-ref-child-of` in `app.common.logic.variants` walks the chain looking for the first ref-shape whose ancestors include a specific parent. Variant switch uses this to locate the equivalent master child in the target variant.
## :touched flags
`:touched` is a set of override-group keywords such as `:geometry-group`, `:fill-group`, and `:text-content-group`. It means a copy diverged from its master for attrs in that sync group.
`sync-attrs` in `app.common.types.component` maps attrs to groups. `set-touched-group` is the legitimate setter; the central `set-shape-attr` path calls it only for copies and only when ignore flags allow it.
Masters are not normally touched through `set-shape-attr`, but touched flags can appear on master shapes through cloning/duplication paths. `add-touched-from-ref-chain` in `app.common.logic.variants` unions touched flags from ancestors into the copy being processed, so upstream/master touched state can affect downstream switch behavior.
## Swap slots and positional matching
- A swap slot (stored via `ctk/set-swap-slot`, a `:touched` group `swap-slot-<uuid>`) marks a copy sub-head that was SWAPPED to another component; `compare-children` then pairs it to the main child by slot instead of by `shape-ref`.
- Copy sub-heads without a slot are paired to main children by `shape-ref` (seek, not index). `find-near-match` (positional) is only a validator/repair heuristic; validity requires membership of the ref among the near-main parent's children, not index equality (`mem:common/file-validation`).
- Copy child ORDER converges to the main's via the async sync (`moved` branch of `compare-children`); local code must never reorder copy children directly (guards in `:mov-objects`/`:reorder-children`).
## Cloning paths
`make-component-instance` in `app.common.types.container` produces a clean component copy through `update-new-shape`, dissociating attrs such as `:touched`, `:variant-id`, and `:variant-name` on cloned shapes.
`duplicate-component` in `app.common.logic.libraries` creates a new component master by cloning existing component shapes, setting component metadata, and applying a position delta. It does not have the same clean-copy semantics as `make-component-instance`, so inherited attrs on the source can matter.
When a bug depends on touched state, identify which cloning path produced the shape before changing sync logic.
## Variant containers
A variant container is a frame with `:is-variant-container true`. Its children are variant masters with `:variant-id` pointing at the container and `:variant-name` naming the variant value. Component records in the library carry `:variant-properties`.
Predicates are broad: `ctk/is-variant?` checks `:variant-id` and applies to both variant master shapes and component rows; `ctk/is-variant-container?` checks the container shape flag.
Moving/dropping a shape into a variant container through the move-to-frame path can auto-convert it into a variant via `generate-make-shapes-variant`, which may duplicate the underlying component. Treat drag/drop into variant containers as a component/variant operation, not a plain reparent.

View File

@ -1,58 +0,0 @@
# Common Component and Change Debugging Recipes
Keep source changes out of these recipes unless the task requires a durable fix.
## Inspect recent workspace changes
From `cljs_repl` after triggering an action:
```clojure
(let [items (get-in @app.main.store/state [:workspace-undo :items])
n (count items)]
(->> items
(drop (max 0 (- n 5)))
(map-indexed (fn [i it]
{:idx (+ i (max 0 (- n 5)))
:tags (:tags it)
:n (count (:redo-changes it))
:types (frequencies (map :type (:redo-changes it)))
:ids (mapv :id (:redo-changes it))}))))
```
To inspect operations within the latest `:mod-obj`:
```clojure
(let [items (get-in @app.main.store/state [:workspace-undo :items])
mod-obj (->> (:redo-changes (last items))
(filter #(= :mod-obj (:type %)))
first)]
(:operations mod-obj))
```
## Trace variant switch attribute copying
To capture what `update-attrs-on-switch` saw during a real UI swap, patch it temporarily in `cljs_repl`:
```clojure
(def orig (deref #'app.common.logic.libraries/update-attrs-on-switch))
(def trace-buf (atom []))
(set! app.common.logic.libraries/update-attrs-on-switch
(fn [& args]
(swap! trace-buf conj
(let [[_ curr prev _ _ origin _] args]
{:curr (select-keys curr [:name :x :y :selrect :points :touched])
:prev (select-keys prev [:name :x :y :selrect :points :touched])
:origin-ref (select-keys origin [:id :name :x :y :width :height :selrect])}))
(apply orig args)))
;; trigger UI action, then inspect @trace-buf
(set! app.common.logic.libraries/update-attrs-on-switch orig)
```
Runtime patching is faster than adding temporary source instrumentation and avoids recompilation cleanup. Restore the var or reload the frontend when finished.
## Test-side helpers
- Use `thf/dump-file file :keys [...]` to print a shape tree with selected keys during common tests.
- Prefer production-path helpers such as `cls/generate-update-shapes` plus `thf/apply-changes` for shape mutations.
- For component swaps with keep-touched behavior, use `tho/swap-component-in-shape` with `{:keep-touched? true}`.
- Temporary `prn` calls in production code are acceptable while investigating but should be removed before committing.

View File

@ -1,7 +0,0 @@
# Component swap and variant switch
- Start at `app.main.data.workspace.variants` and `app.main.data.workspace.libraries/component-swap`. Variant switch uses `keep-touched?` to preserve eligible overrides; `component-multi-swap` intentionally passes false.
- A swap re-reads the shape from live page objects before building changes: sibling swaps or layout can move it, and a missing shape becomes a no-op. Do not use a closed-over shape as the current location.
- `app.common.logic.libraries/generate-component-swap` creates the replacement; when keeping touched state, `app.common.logic.variants/generate-keep-touched` walks the old children, incorporates touched groups from their ref chains and finds corresponding shapes in the target. Model and slot semantics are in `mem:common/component-data-model`.
- `update-attrs-on-switch` compares the old copy, fresh target and origin master before carrying an override. Preserve its guards for differing masters, shape types, auto text and composite geometry; `:selrect`, `:points` and path content need special handling, including fixed-layout cases. Do not assume an apparently untouched local shape lacks inherited touched groups, or that the roots have the same position.
- Use `app.common.test-helpers.compositions/swap-component-in-shape` with `:keep-touched?` to exercise the production path. Nearby cases in `common/test/common_tests/logic/variants_switch_test.cljc` cover swap and touched behavior; follow `mem:common/testing` for runtime and fixture guidance.

View File

@ -0,0 +1,46 @@
# Components, variants and file integrity
Start at `app.common.types.component`, `app.common.types.container`, `app.common.logic.libraries` and `app.common.logic.variants`. Referential validation and repair live in `app.common.files.validate` and `app.common.files.repair`.
## Model and synchronization
- A shape can simultaneously be a main instance, a copy or an instance root. Main instances carry `:main-instance` and `:component-id`; copies carry `:shape-ref`; roots carry `:component-root` and component identity. Nested instances make these roles overlap.
- `:shape-ref` chains can cross files. `find-ref-shape` and `get-ref-chain-until-target-ref` follow them; the nearest component head and the outermost instance root are not interchangeable.
- `:touched` stores override groups from `sync-attrs`. `set-shape-attr` marks copies through `set-touched-group`, subject to ignore flags; `:position-data` is derived and never touched. Geometry and content-path comparisons use approximate equality, but width and height are excluded from the `is-geometry?` branch.
- Main shapes can acquire touched flags through cloning. `add-touched-from-ref-chain` can propagate upstream flags during variant switch, so a locally untouched shape can still act touched. `make-component-instance` cleans attrs including `:touched`, `:variant-id` and `:variant-name`; duplicating a component master does not have identical clean-copy semantics. Identify the creation path before diagnosing touched.
- Swap slots are touched groups `swap-slot-<uuid>` on swapped copy sub-heads. Sync matches those by slot; other children match by `shape-ref`, not index. Child order converges through async sync. `:mov-objects` and `:reorder-children` guard copy structure unless a sync or swap sets `allow-altering-copies`; new structural changes need the same guard.
- Deleting inside a component main propagates to referencing copies transitively across pages to prevent dangling refs. `generate-delete-shapes` skips propagation for the main root itself and for `allow-altering-copies` flows. Adding a shape to a copy parent clears its `:remote-synced` unless `ignore-touched`.
## Variants and swap
- A variant container is a frame with `:is-variant-container`; its variant masters refer to it via `:variant-id` and have `:variant-name`. Component rows carry `:variant-properties`. `is-variant?` applies to rows and shapes. Moving a shape into a variant container can convert it into a variant and duplicate the component, not merely reparent it.
- Frontend `component-swap` re-reads the shape from live page objects: sibling swaps or layout can move it, and a missing shape is a no-op. Variant switch uses `keep-touched?` for eligible overrides; `component-multi-swap` intentionally passes false.
- `generate-component-swap` makes the replacement; `generate-keep-touched` walks old children, incorporates ref-chain touched groups and finds corresponding target shapes. `update-attrs-on-switch` compares the old copy, fresh target and origin master. Preserve guards for differing masters, shape types, auto text and composite geometry, including fixed-layout and path cases; do not assume roots have identical positions.
## Referential integrity and repair
- Referential and semantic validation in `app.common.files.validate` runs for files with `"components/v2"`; it visits the root, orphan shapes and component records. `validate-file!` raises `:validation` / `:referential-integrity` with details. `update-file` uses change-scoped validation of affected pages and components; schema validation is separate in `mem:common/change-application`.
- `repair-file` produces redo changes that callers must apply or persist. `repair-file-until-valid` stops on no errors, unchanged data, a stable error fingerprint without `:shape`, or its iteration limit. Check the fingerprint before another pass; backend `PointerMap` equality is pointer identity. Multiple `:set` repairs on one shape can need multiple passes because each repair starts from the original file data.
- For `:ref-shape-not-found`, repair can restore a local component's `:main-instance-id` when the recorded main is missing but its matching main exists on the recorded page. Otherwise it tries a near-main reassignment or detaches the copy subtree.
- `:missing-slot` is a real swap only when the copy sub-head's `:shape-ref` is no longer a child of the near main parent. A sibling at a different position is a reorder, not a swap; assigning a slot blocks normal sync. `find-near-match` is a repair heuristic, not a positional validity rule. Migration 0019 uses the same membership rule; see `mem:common/file-migrations`.
## Diagnosis and tests
- For production-path swap tests use `app.common.test-helpers.compositions/swap-component-in-shape` with `:keep-touched?`; see `common/test/common_tests/logic/variants_switch_test.cljc` and `mem:common/testing`. `thf/dump-file` prints shape trees. Use production change helpers for fixture mutations.
- To inspect recent changes in a live workspace, examine `[:workspace-undo :items]`, including each item's `:tags`, `:redo-changes` and `:operations` for `:mod-obj`. See `mem:frontend/cljs-repl` for runtime selection and temporary instrumentation. Restore patched vars and remove source traces after debugging.
- To trace `update-attrs-on-switch` during a UI swap, save the original var, wrap it to capture current, previous and origin shapes, then restore it:
```clojure
(def orig (deref #'app.common.logic.libraries/update-attrs-on-switch))
(def trace-buf (atom []))
(set! app.common.logic.libraries/update-attrs-on-switch
(fn [& args]
(swap! trace-buf conj
(let [[_ curr prev _ _ origin _] args]
{:curr (select-keys curr [:name :x :y :selrect :points :touched])
:prev (select-keys prev [:name :x :y :selrect :points :touched])
:origin-ref (select-keys origin [:id :name :x :y :width :height :selrect])}))
(apply orig args)))
;; Trigger the UI action and inspect @trace-buf.
(set! app.common.logic.libraries/update-attrs-on-switch orig)
```

View File

@ -35,13 +35,11 @@ Geometry and layout:
Change pipeline, validation, and migrations:
- Change records, undo/redo architecture, changes-builder API, and production-path mutation guidance: `mem:common/changes-architecture`.
- Change application, shape-tree edits and second-pass touched behavior: `mem:common/change-application`. File validation and repair: `mem:common/file-validation`.
- Change application, shape-tree edits and change-scoped schema validation: `mem:common/change-application`.
- Adding, renumbering or replacing a file migration: `mem:common/file-migrations`.
Components, variants, and debugging:
- Component/variant data model, ref chains, touched override semantics, and cloning paths: `mem:common/component-data-model`.
- Component swap, variant switch, and keep-touched pipeline: `mem:common/component-swap-pipeline`.
- Live inspection snippets, temporary runtime patching, and test-side debugging helpers for common change/component behavior: `mem:common/component-debugging-recipes`.
- Components, variants, referential integrity, repair and diagnosis: `mem:common/components`.
Text and tests:
- Shared text data conversion, DraftJS compatibility, modern text content, and derived position data: `mem:common/text-subtleties`.

View File

@ -1,8 +0,0 @@
# Common file validation and repair
- Start at `app.common.files.validate` and `app.common.files.repair`. Full referential and semantic validation runs when file features include `"components/v2"`; it visits the root and orphan shapes, then component records. `validate-file!` raises `:validation` / `:referential-integrity` with details.
- `update-file` uses change-scoped referential and schema validation. `touched-page-ids` selects pages for the schema check while non-page data is checked whole. Register a new change type as page-writing or file-level; an unknown type falls back to validating the whole file, which loads every page.
- `repair-file` produces redo changes rather than mutating data; callers must apply or persist them. `repair-file-until-valid` stops on no errors, unchanged data, a stable error fingerprint without `:shape`, or its iteration limit. Check the fingerprint before another repair pass; backend `PointerMap` equality is pointer identity. Multiple `:set` repairs on one shape can require multiple passes because each repair starts from the original file data.
- For `:ref-shape-not-found`, repair can restore a local component's `:main-instance-id` when the recorded main is missing but the matching main exists on its recorded page. Otherwise it tries a near-main reassignment or detaches the copy subtree.
- `:missing-slot` is a real swap only when a copy sub-head's `shape-ref` is no longer a child of the near main parent. A sibling in a different position is a reorder, not a swap: assigning a slot would block normal component sync. Migration 0019 follows the same membership rule; see `mem:common/file-migrations`.
- For change application see `mem:common/change-application`; for copy and slot semantics see `mem:common/component-data-model`.

View File

@ -7,4 +7,4 @@
- Helpers live under `common/src/app/common/test_helpers/`. Tests using label-to-UUID helpers need `(t/use-fixtures :each thi/test-fixture)` to reset labels between tests. Inspect the builders there rather than recreating common file, component or variant setup.
- Prefer production-path mutations such as `cls/generate-update-shapes` with `thf/apply-changes`; the latter validates by default. Disable validation only for intentionally malformed intermediate state. For swaps that keep touched state use `tho/swap-component-in-shape` with `{:keep-touched? true}`. `add-variant-with-copy` does not take child position params; move them after creation. For geometry-sensitive setup see `mem:common/geometry-invariants`.
- `sg/sample` is unseeded by default. If a test filters for a subtype, fix the seed and verify the subtype exists; otherwise `first` can yield nil and later produce a typeless shape.
- For change and component debugging see `mem:common/component-debugging-recipes`.
- For component and referential-integrity debugging see `mem:common/components`.

View File

@ -8,7 +8,7 @@ printf '(shadow.cljs.devtools.api/repl-runtimes :main)\n' | timeout 10 npx shado
printf '(shadow.cljs.devtools.api/cljs-eval :main "<cljs-code>" {:client-id 5})\n' | timeout 10 npx shadow-cljs clj-eval --stdin
```
- Inspect `app.main.store/state` for workspace metadata and selection; use `@app.main.refs/workspace-page-objects` for current page objects. Internal `:rect` and `:frame` correspond to Plugin API rectangle and board. Component head and outermost instance root differ for nested instances; see `mem:common/component-data-model`.
- Inspect `app.main.store/state` for workspace metadata and selection; use `@app.main.refs/workspace-page-objects` for current page objects. Internal `:rect` and `:frame` correspond to Plugin API rectangle and board. Component head and outermost instance root differ for nested instances; see `mem:common/components`.
- Navigate with `app.main.data.common/go-to-workspace`, supplying team, file and page IDs explicitly; omitted values can fall back to the current workspace. `app.main.store/emit!` dispatches an event and returns nil, not the watch result. Helpers in `app.plugins.utils` locate shapes, files and components.
- A store captures `on-event` when created, so replacing the var does not intercept its events. Subscribe to `app.main.store/stream` instead and dispose the subscription. Mutable CLJS hooks can be patched for debugging; restore them or reload afterward. For a temporary RPC spy wrap the target `app.main.repo/cmd!` multimethod's default method and remove the method after use.
- `(.reload js/location)` clears runtime patches and reloads saved state; it can discard unsaved edits. For crash diagnosis and recovery see `mem:frontend/handling-crashes`; for component and change tracing see `mem:common/component-debugging-recipes`. Development browser-console commands are defined in `frontend/src/debug.cljs`.
- `(.reload js/location)` clears runtime patches and reloads saved state; it can discard unsaved edits. For crash diagnosis and recovery see `mem:frontend/handling-crashes`; for component and change tracing see `mem:common/components`. Development browser-console commands are defined in `frontend/src/debug.cljs`.

View File

@ -3,4 +3,4 @@
- Use `mem:frontend/composable-component-tests/cljs` to test component behavior through workspace events in a minimal frontend harness. Use `mem:frontend/composable-component-tests/plugin` to exercise that behavior through the Plugin API in the full browser app.
- Bind each producing operation or strategy once and query that same instance for what it produced, which choice ran, or whether it applied. Reading the document directly for those answers loses the identity of the operation that ran in a variant and duplicates retrieval logic.
- Drive real changes, workspace events or Plugin API calls; direct writes bypass the automatic propagation under test. Resolve targets by role when each operation runs, so a role rebound by a previous step still works. Compose only valid variants rather than treating invalid combinations as skipped coverage.
- For component behavior and swap semantics see `mem:common/component-data-model` and `mem:common/component-swap-pipeline`; for test selection see `mem:frontend/testing`.
- For component behavior, swap semantics and integrity see `mem:common/components`; for test selection see `mem:frontend/testing`.