mirror of
https://github.com/penpot/penpot.git
synced 2026-11-26 21:00:32 +00:00
📚 Separate common file migration guidance
Keep cross-file change and validation rules in focused memories. Route migration work to its own note and point to code for implementation details, including the current SVG repair. AI-assisted-by: gpt-6.2-sol
This commit is contained in:
parent
0b4bb4b832
commit
b9e35937e0
@ -1,46 +1,7 @@
|
||||
# File Mutations: Changes and Undo Architecture
|
||||
# File changes and undo
|
||||
|
||||
Penpot mutates file data through change records. A change set is both the persistence payload and the basis for undo/redo, so UI actions, tests, backend file updates, and library/file tooling should drive the production change pipeline instead of ad hoc object-map mutation.
|
||||
|
||||
## Change shape
|
||||
|
||||
Each change is a map such as `{:type ... :id ... :page-id ...}`. Common families:
|
||||
|
||||
- `:add-obj`, `:mod-obj`, `:del-obj`: shape lifecycle. `:mod-obj` contains `:operations`, commonly `{:type :set :attr ... :val ... :ignore-geometry ... :ignore-touched ...}` or `{:type :set-touched ...}`.
|
||||
- `:add-component`, `:mod-component`, `:del-component`: component/library metadata.
|
||||
- Shapes stored inside the component record (deleted components keep them in `:objects`) are never written as a whole map: `mod-component` carries only component metadata by default, and shapes travel as `:mod-obj`/`:add-obj`/`:del-obj` changes scoped with `:component-id`. `pcb/update-component` has an `:objects? true` option for the two repairs that move or clear that key, and `ctkl/mod-component` reads an absent `:objects` as "leave the stored shapes alone" (only an explicit `nil` drops them). Before this, one component swap resent the full object map of every deleted component it touched (~6 MB in the request); do not reintroduce it.
|
||||
- `:add-children`, `:remove-children`, `:reg-objects`: tree and object-map edits.
|
||||
- `:set-option`, `:add-page`, `:mov-page`, and related file/page metadata changes.
|
||||
|
||||
Each transaction carries `:redo-changes` and inverse `:undo-changes`. The undo stack stores transactions and can move its index backward/forward.
|
||||
|
||||
## Batches that were already built
|
||||
|
||||
`common/src/app/common/files/changes_merge.cljc` (alias `mch`) rewrites a finished batch into an equivalent smaller one, without touching file data.
|
||||
- `mch/merge-reg-objects`: the component sync emits one `:reg-objects` per touched shape, so a component swap carries hundreds of them for a handful of groups. It collapses them into one per container, union of `:shapes`, moved to the end of the batch so a group is always recomputed after the shapes that resized it. Applied to both redo and undo, on every commit (`frontend/src/app/main/data/changes.cljs`) and again within each buffered commit before queueing (`frontend/src/app/main/data/persistence.cljs`). Keep commits separate: the backend can reject them by `commit-id`, so persistence must not fuse changes across commit boundaries. Measured on a real swap: 291 `:reg-objects` become 36, the whole batch goes 806 changes / 6.4 MB to 551 / 324 KB.
|
||||
|
||||
## changes-builder API
|
||||
|
||||
`common/src/app/common/files/changes_builder.cljc` (usually alias `pcb`) is the fluent builder. Start from `(pcb/empty-changes <it> <page-id>)` or `(pcb/empty-changes nil <page-id>)` for tests.
|
||||
|
||||
High-value builder operations:
|
||||
- `pcb/add-page changes page`: derives the ID from the whole page. The redo change still carries both `:id` and `:page`; the undo deletes that same ID. `pcb/add-empty-page` takes an ID and name instead.
|
||||
- `pcb/with-page-id`, `pcb/with-objects`, `pcb/with-library-data`: set context for following operations.
|
||||
- `pcb/update-shapes ids update-fn`: emits `:mod-obj` with diff-derived `:set` ops. Options include `{:with-objects? true}`, `{:ignore-touched true}`, and `{:attrs #{...}}`.
|
||||
- `pcb/add-objects`, `pcb/change-parent`, `pcb/remove-objects`, `pcb/resize-parents`: shape/tree edits.
|
||||
- `pcb/add-component`, `pcb/update-component`, `pcb/mod-component`: component/library edits. Repairs that fix shapes inside a component use `pcb/with-container` + `pcb/with-objects` + `pcb/update-shapes` so the changes come out scoped with `:component-id`.
|
||||
- `pcb/set-translation? true`: marks the whole change set as translation-only, which lets component sync skip expensive work.
|
||||
|
||||
## Applying changes in tests
|
||||
|
||||
`thf/apply-changes` in `app.common.test-helpers.files` is the test analog of the production applier. It validates by default; pass `:validate? false` only for intentionally-invalid intermediate states.
|
||||
|
||||
The applier uses the same `process-operation` multimethod as production (`common/src/app/common/files/changes.cljc`), so tests that use it exercise production behavior.
|
||||
|
||||
## :touched and geometry
|
||||
|
||||
For component touched semantics and sync groups, read `mem:common/component-data-model`. For the exact `set-shape-attr` / second-pass behavior during change application, read `mem:common/file-change-validation-migration-subtleties`. For transform-specific ignore-geometry behavior, read `mem:frontend/workspace-transform-subtleties`.
|
||||
|
||||
## Inspection
|
||||
|
||||
To inspect what a UI action emitted, use `mem:frontend/cljs-repl` with the snippets in `mem:common/component-debugging-recipes` rather than adding temporary source instrumentation.
|
||||
- File changes are both the persistence payload and the basis for undo. Use the production change pipeline rather than editing object maps directly. Start in `app.common.files.changes` for schemas and application, `app.common.files.changes-builder` for redo/undo construction, and `app.common.files.changes-merge` for compaction.
|
||||
- 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 and validation see `mem:common/file-change-validation-migration-subtleties`. For live inspection of emitted changes, see `mem:common/component-debugging-recipes`.
|
||||
|
||||
@ -2,17 +2,6 @@
|
||||
|
||||
`common/` intro: shared CLJC for frontend, backend, exporter, library/file tooling, tests. Small semantic changes can affect multiple runtimes.
|
||||
|
||||
## Stable namespace map
|
||||
|
||||
- `app.common.data` and `app.common.data.macros`: generic data helpers and performance macros that do not depend on Penpot domain entities.
|
||||
- `app.common.types.*`: shared shape/file/page/component/token data types, schemas, predicates, and entity-local operations. `app.common.types.organization` contains organization schemas, `apply-organization`, and fail-closed organization/team permission rules (`allowed?`, `can-send-invitations?`).
|
||||
- `app.common.files.*`: file-level operations, shape tree helpers, change application, migrations, validation, and undo/redo-related logic.
|
||||
- `app.common.logic.*`: higher-level workflows/algorithms over files, shapes, components, variants, libraries, tokens, etc.
|
||||
- `app.common.geom.*`: geometry helpers and transformations.
|
||||
- `app.common.schema` / `app.common.schema.*`: Malli abstraction layer.
|
||||
- `app.common.math`, `app.common.time`, `app.common.uuid`, `app.common.json`, etc.: cross-runtime utilities.
|
||||
- `app.common.test_helpers.*`: test builders and production-path helpers.
|
||||
|
||||
## Layering and cross-runtime rules
|
||||
|
||||
Use reader conditionals for platform-specific code. Because CLJC runs on JVM and CLJS targets, avoid assuming browser-only or JVM-only behavior unless the reader conditional isolates it.
|
||||
@ -28,9 +17,7 @@ Some legacy code violates this layering; do not copy those violations into new c
|
||||
|
||||
## Build-mode dependent laziness
|
||||
|
||||
`app.common.data.macros/lazy-delay` returns a delay whose expression is evaluated eagerly by default. Only the builds that set the `app.common.data.macros/lazy-delay?` closure define to `true` defer it to the first deref; every production build does (frontend `main` and `worker`, exporter, library), so the Closure compiler replaces the constant and drops the eager branch. On the JVM it is always eager.
|
||||
|
||||
`app.common.schema/check-fn` resolves its schema through it: an invalid schema definition fails when the namespace loads in development and in tests, and only on the first check call in production. The other lazily built parts of `check-fn` (validator and explainer) are always deferred.
|
||||
`app.common.schema/check-fn` resolves schemas through `app.common.data.macros/lazy-delay`: an invalid schema can fail on namespace load in development and JVM tests, but at first use in production CLJS. See the macro docstring and each target's `:closure-defines` for the evaluation rules.
|
||||
|
||||
## Focused memory routing
|
||||
|
||||
@ -39,6 +26,7 @@ Some legacy code violates this layering; do not copy those violations into new c
|
||||
Model, schema, and persistence shape:
|
||||
- File/page/shape/component attr changes, import/export surfaces, inspector/codegen, and cross-module checklist: `mem:common/data-model-change-checklist`.
|
||||
- Token data structures, token import/export, active theme/set semantics, and schema/coercion behavior: `mem:common/tokens-schema-subtleties`.
|
||||
- For organization and team permission rules shared across runtimes, start at `app.common.types.organization`.
|
||||
|
||||
Geometry and layout:
|
||||
- Shape geometry invariants, redundant geometry fields, and geometry-sensitive tests: `mem:common/geometry-invariants`.
|
||||
@ -47,7 +35,8 @@ 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, validation/repair, migrations, and second-pass touched behavior: `mem:common/file-change-validation-migration-subtleties`.
|
||||
- Change application, shape-tree edits, validation/repair, and second-pass touched behavior: `mem:common/file-change-validation-migration-subtleties`.
|
||||
- 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`.
|
||||
@ -58,7 +47,3 @@ Text and tests:
|
||||
- Shared text data conversion, DraftJS compatibility, modern text content, and derived position data: `mem:common/text-subtleties`.
|
||||
- Common test commands, helper conventions, production-path test mutations, and runtime coverage choices: `mem:common/testing`.
|
||||
- Cross-cutting testing principles, anti-patterns, and verification checklist: `mem:testing`.
|
||||
|
||||
## Areas without focused memories
|
||||
|
||||
Common areas with little or no dedicated memory include colors, media/SVG helpers, path operations, thumbnail helpers, generic pools, weak refs, and some utility namespaces. Treat work there as source/test-led unless a focused memory exists.
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
- Do not treat nil as a distinct persisted state from absence. Import/export and cleanup paths may filter nil attrs away.
|
||||
- Avoid Clojure-special naming in exported object attrs, especially boolean names ending in `?`; exported/imported data must survive JSON/SVG/Transit and external tooling.
|
||||
- Any new shape attr that participates in component sync must be listed in `app.common.types.component/sync-attrs` with the correct touched group. Attrs absent from `sync-attrs` are ignored by component synchronization.
|
||||
- Shape `:svg-attrs` keys are kebab-case (`fill-rule`, not `fillRule`): birth (`app.common.svg/attrs->kebab-props`, applied everywhere data lands on a shape) normalizes any outside spelling through the `svg-props` whitelist, and render boundaries (`get-svg-props`, `render-xml*`, `svg-node*`) translate back to camelCase for React. `:svg-defs` node attrs follow the same rule recursively; svg-raw `:content` attrs are kebab-ized spelling-only, never filtered — the sidebar reads `:stroke-style`, which is outside the whitelist. Non-spec attrs Penpot keeps live in `penpot-extra-attrs` (seeded with `:stroke-style`) and travel in source spelling. Excluded, each with its reason: `:tag` values (React and tag sets need them verbatim; the schema decoder restores keywords from stored strings), outer `:svg-defs` keys (id strings at birth, keywords or strings after JSON decode — accept both), all values (the kebab reader never touches values). Repair sites: birth plus migration `0035-fix-shape-svg-attrs-and-defs` (replaces the withdrawn `0021`); the binfile cleaner carries no svg repair.
|
||||
- Store SVG attribute keys in kebab-case (`fill-rule`, not `fillRule`) and convert to React spelling only at render boundaries. Use `app.common.svg/attrs->kebab-props` for shape and defs-node attrs; for svg-raw `:content`, normalize spelling without filtering unknown keys (the sidebar reads `:stroke-style`). Don't normalize tags, attribute values or outer defs IDs as though they were attribute keys; defs IDs can decode as keywords or strings. Normalize when constructing the shape; legacy data goes through the SVG repair in `app.common.files.migrations`, not the binfile cleaner.
|
||||
|
||||
## Cross-module update checklist
|
||||
|
||||
@ -21,6 +21,6 @@ When changing the file data model, check the relevant paths:
|
||||
|
||||
## Migrations
|
||||
|
||||
Existing files should keep working unchanged when possible. If absence cannot preserve old behavior, add a migration and preserve append/order semantics described in `mem:common/file-change-validation-migration-subtleties`.
|
||||
If an absent attribute cannot preserve old behavior, see `mem:common/file-migrations` for migration and ordering rules.
|
||||
|
||||
Model changes can also require file feature flags or migration metadata updates; check nearby migrations and `common/src/app/common/features.cljc` before inventing a new pattern.
|
||||
|
||||
@ -28,13 +28,4 @@
|
||||
|
||||
## Migrations
|
||||
|
||||
- Prefer optional attrs/default behavior so old files continue working without migration. If absence cannot preserve old behavior, add a migration.
|
||||
- Migrations are an ordered set mixing legacy version-derived ids and newer named ids. Keep append order stable; `migrate` applies the set difference between available migrations and file migrations.
|
||||
- `migrate-file` synthesizes legacy migration ids from old numeric versions when `:migrations` is absent, migrates legacy features, and records feature flags created through `cfeat/*new*`.
|
||||
- When a file had no previous `:migrations`, `migrate-file` marks all migrations as migrated in metadata so callers persist the complete migration set, not only transformations that changed data.
|
||||
- Closed schemas (`schema:stroke-attrs` and others) reject a key that was dropped from the declaration, so removing a declared attr needs a migration in the same change, for data already written with it.
|
||||
- Rebase collision on a migration number: upstream keeps the id. Renumber the branch migration to the next free one, keep it last in `available-migrations`, and rename everything that spells the number — its test file and namespace (`files_migrations_00NN_test.cljc`), the test names, and comments in production code or memories that name it.
|
||||
- Withdrawing a migration id: remove both the `defmethod` and the id from `available-migrations`; the replacement migration subsumes it and files that recorded the old id re-migrate through the replacement (persisted `:migrations` keep the old id via union — do not rewrite them, including playwright fixture JSONs). Idempotent/pure-cleanup migrations only; never withdraw one whose transform must not run again unless the replacement is safe for those files. Precedents: "0021-fix-shape-svg-attrs" -> "0035-fix-shape-svg-attrs-and-defs"; "legacy-36" -> "0036-clear-nil-keys-in-objects".
|
||||
- A shipped migration whose behavior must change AND reach every file (most files already recorded its id, so `migrate` skips it): rename it to `<id>-v2` and swap the old id for the new one in `available-migrations` at the SAME position. Precedents: `0002-normalize-bool-content-v2`, `0003-convert-path-content-v2`, `0008-fix-library-colors-v4`, and `0035-fix-shape-svg-attrs-and-defs` withdrawing `0021-fix-shape-svg-attrs`. Files keep the old id in `:migrations`, which is harmless because `migrate` diffs against the available set. Cost: one full pass over every file on its next read (the `get-file` ETag hashes `available-migrations`, so clients refetch).
|
||||
- The alternative is patch the old id plus add a new migration id for the files that already applied it. Then the position in the list decides which repair runs first: a coerce-then-drop repair must come before a drop-only one, or the strings are gone before they can be parsed.
|
||||
- `0033-normalize-main-instance-names-v2` repairs the container before its naming walk: child ids stored as strings are parsed with `uuid/coerce`, ids missing from `:objects` are dropped, duplicates are removed (the one `0032` adds when a child is stored as a string). The walk only re-assocs a shape when the normalization changed it (`identical?` on the normalized shape), so a healthy container keeps its `ObjectsMap` instance: no `modified` flag, no page rewrite. `0035-fix-dangling-children` prunes whatever is left.
|
||||
For migration IDs, ordering and compatibility with previously saved files, see `mem:common/file-migrations`.
|
||||
|
||||
7
.serena/memories/common/file-migrations.md
Normal file
7
.serena/memories/common/file-migrations.md
Normal file
@ -0,0 +1,7 @@
|
||||
# File migrations
|
||||
|
||||
- Start at `app.common.files.migrations` for `available-migrations` and transforms. Prefer optional attributes with compatible defaults. If removing a key from a closed schema, migrate existing data in the same change: the new schema rejects the key, not just its value. See `mem:common/data-model-change-checklist` for consumers.
|
||||
- Keep the ordered registry stable. On a rebase collision, keep the upstream ID, move the unshipped branch migration to the next free number at the end, and update its test file/namespace and all references together.
|
||||
- Once a file records an ID, changing its implementation alone won't run it again. If a safe replacement must run at the same stage, use a new versioned ID at the same position. If adding a separate repair for already-migrated files, check the relative order: a repair that parses a malformed value must run before one that drops it.
|
||||
- Withdraw an ID only when the replacement remains safe on files that already ran it. Remove the old implementation and registry entry; leave historical IDs in saved files and fixtures. A registry change also changes the `get-file` ETag, so clients can refetch and files can migrate on the next read.
|
||||
- Preserve the full applied migration set when upgrading a file that used legacy numeric versions, even when individual transforms are no-ops. For cleanup across pages, preserve the original objects map on a no-op so a healthy page is not marked modified and rewritten.
|
||||
Loading…
x
Reference in New Issue
Block a user