Gallery Folders — Design Document
Status: Shipped 2026-08-18 (7146bc42) — slices 1–6 (see Implementation Plan). Slice 7, a public folder hierarchy, stays blocked.
Overview
A creator with a large body of work outgrows a flat gallery list. The concrete case: a Kaldra folder holding everything for one world, where a handful of characters each need their own pocket of images. Today that forces a choice between one enormous gallery and a flat list of near-duplicate names — Kaldra, Kaldra - Serie, Kaldra - Vex — sitting at the same level as everything else the creator owns.
Gallery folders let a gallery live inside another gallery. A folder is not a new entity: it is an ordinary gallery that happens to have a parent. It still holds images, still has a cover, still has a slug, still retains its own is_public browse/listing flag. Nesting adds organization, and nothing else.
The design's whole ambition is to be unremarkable — no new URL scheme, no new permission model, no new moderation surface, and no relearning of what a gallery is.
Design Goals
- Links never get longer. Existing
g://references keep working, byte for byte. This was the objection that killed the idea the first time it came up, and it turns out to be avoidable. - Reuse the tree substrate that already exists. The admin documentation wiki already ships a generic tree with drag-to-reparent, cycle prevention, and expand/collapse. Gallery folders generalize it rather than growing a second one.
- Horizontal space is sacred. The gallery drawer is narrow, and narrower on mobile. Hierarchy is communicated by visual weight, not by indentation.
- Organization only. Nesting must not become a permission axis, a moderation axis, or a quota axis.
- The tree is always valid. Invalid structures are impossible to create — enforced in the database against direct SQL, not merely discouraged by the UI.
Non-Goals
Deliberately out of scope — several of these a reader would reasonably assume are in:
- More than two levels. Depth is capped at root + one level of subfolders. This is a direct consequence of the no-indent decision: visual de-emphasis carries two tiers legibly and three muddily. Deeper nesting would require reintroducing indentation or switching to drill-in navigation, and neither is worth it for the use case.
- Public hierarchy. Subfolders are an owner-library concept in this feature. The public gallery page is untouched, and no nesting is exposed to anonymous viewers. See Future public hierarchy.
- Recursive deletion. Deleting a parent never deletes its children or their images. There is no "delete subfolders too" option.
- Per-parent slug namespaces. Slugs stay unique per user, so two subfolders under different parents still cannot share a slug. This is the price of keeping links short, and it is the same trade the blog category system already made deliberately.
- Visibility inheritance. A private parent does not hide a public child, and a public parent does not expose a private one.
is_publicstays a local flag on each gallery. - Recursive storage accounting. Quota remains a per-user sum across every image the user owns. A folder's size is its own images; it does not roll up its descendants into the quota check.
- Nesting in the admin console. Moderation works on individual images and has no gallery-tree view. It stays that way.
- Nested "Unsorted". Unsorted is a virtual pseudo-gallery, not a row. It stays pinned at root and cannot be nested or nested into.
- Gallery-level moderation or publish review. Galleries have never had a publish-request workflow, and folders do not introduce one.
- Collaborator or project-scoped structural edits. Placement is an owner-library operation.
- Changing a gallery's owner. Ownership becomes immutable after insertion (see below).
Folder semantics
| Property | Behavior |
|---|---|
| Depth | Two levels. Every gallery may hold images; only root galleries may have child galleries. Enforced in the database, not by UI convention. |
| Ownership | Immutable after insertion — except an account merge, which hands every gallery of the merged-away account to the surviving one in a single transaction, parents before children. A parent and child therefore always share an owner, and cross-owner edges cannot be introduced by any route. |
| Slug | Unique per user, unchanged. A subfolder's slug is a peer of every other gallery's slug. |
| Visibility | Local is_public per gallery. No inheritance in either direction. |
| Deleting a parent | Children are promoted into the deleted parent's position among the roots, preserving their relative order. Children and their images survive; the deleted gallery's own images are deleted and cleaned up from storage exactly as today. |
| Cover image | Still drawn from the gallery's own images. A folder does not borrow a descendant's cover. |
| Ordering | Galleries gain an explicit sort_order within their parent group. Today they have none and are ordered by creation date. |
| Counts | A gallery's image count stays its own. The list additionally exposes a descendant count so a collapsed folder can say what is hidden inside it. |
Why links stay short
A g:// reference names an owner, a gallery slug, and an image slug:
g://pastor-ashe/kaldra-mainline/portrait-01
Gallery slugs are unique per user, not per parent, and reference resolution matches on the owner and the gallery slug alone. Nesting changes where a gallery appears in a list; it does not change how it is addressed. A subfolder resolves by its own short slug from day one, and every reference written before folders existed keeps resolving unchanged.
This mirrors the call the blog category system made for the same reason — a globally unique slug so that two categories in different branches never collide and the URL never has to spell out the path.
Data model
The structural invariant
A pure ancestor-walk guard is insufficient here, and the blog category trigger it would be modelled on demonstrates why. That trigger inspects only the chain above the row being changed. Under a two-level cap, moving a root that already has children underneath another root passes an ancestor check — the moved row lands at depth 2 — while silently pushing its children to depth 3.
The rule that closes this without any descendant traversal:
A gallery may be given a parent only if it has no children of its own, and only if that parent is itself a root owned by the same user.
The guard is the trigger, and the trigger locks
Application functions are not the enforcement boundary — direct SQL must not be able to produce an invalid tree. Two concurrent reciprocal moves (A → B and B → A) each pass validation independently under READ COMMITTED and commit a cycle, so the lock lives inside the trigger, not only in the calling function:
CREATE TRIGGER trg_galleries_structure_guard
BEFORE INSERT OR UPDATE OF parent_id, user_id ON galleries
FOR EACH ROW EXECUTE FUNCTION fn_galleries_structure_guard();
The guard, in order:
- Rejects any
user_idchange on update — ownership is immutable after insertion. Without this, a directUPDATE galleries SET user_id = ...creates a cross-owner edge without ever firing aparent_idtrigger. The one exception is an account merge: it sets the transaction-localeod.gallery_owner_transferto exactly that source and target, moves root galleries before their subfolders (so the checks below pass unchanged), and clears it. Nothing else may change an owner. - Acquires
pg_advisory_xact_lock(NEW.user_id, hashtext('gallery_structure'))as its first structural act, before reading any other row — so concurrent structural writes for one user serialize. - Only then re-reads and validates the tree: the target parent exists, is owned by the same user, and has
parent_id IS NULL; the row being moved has no children; the row is not its own parent.
Serializing structural writes per user costs nothing in practice — a creator reorganizes their library by hand, not concurrently at scale.
Error contract
The guard raises with SQLSTATE P0001, which the API error middleware maps to 409 BusinessRuleViolation carrying the raised message. It must not use check_violation (23514), which is unmapped and falls through to a generic 500 DatabaseError — the user would see "A database error occurred" instead of "only top-level galleries can contain subfolders". Ownership rejections raise 42501, which maps to 403.
That message has to survive to the surface: the shared tree hook's error path currently calls a parameterless onError, discarding whatever the server said. Generalizing it to propagate the server message is part of the substrate work.
Columns and migration
Order must be preserved through the migration. Adding sort_order INTEGER NOT NULL DEFAULT 0 in one step would give every existing gallery the same value, collapsing today's newest-first ordering into an arbitrary tie — a silent regression of the "a flat library is unchanged" invariant. The migration is three-phase, and the FK is separately named and catalog-guarded so a partial run can be repaired — an inline ADD COLUMN IF NOT EXISTS ... REFERENCES cannot re-add a missing constraint once the column exists. This follows the pattern the existing cover-image FK already uses.
-- 1. Add nullable
ALTER TABLE galleries ADD COLUMN IF NOT EXISTS parent_id INTEGER NULL;
ALTER TABLE galleries ADD COLUMN IF NOT EXISTS sort_order INTEGER NULL;
-- Named, catalog-guarded FK (repairable after a partial run)
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_galleries_parent') THEN
ALTER TABLE galleries
ADD CONSTRAINT fk_galleries_parent
FOREIGN KEY (parent_id) REFERENCES galleries(id) ON DELETE SET NULL;
END IF;
END $$;
-- 2. Backfill preserving the current newest-first order
UPDATE galleries g SET sort_order = s.rn
FROM (
SELECT id, ROW_NUMBER() OVER (
PARTITION BY user_id ORDER BY created_at DESC, id DESC
) - 1 AS rn
FROM galleries
) s
WHERE g.id = s.id AND g.sort_order IS NULL;
-- 3. Then pin the constraint
ALTER TABLE galleries ALTER COLUMN sort_order SET DEFAULT 0;
ALTER TABLE galleries ALTER COLUMN sort_order SET NOT NULL;
CREATE INDEX IF NOT EXISTS idx_galleries_owner_placement
ON galleries (user_id, parent_id, sort_order, id);
CREATE INDEX IF NOT EXISTS idx_galleries_parent
ON galleries (parent_id);
Creation stays newest-first without resequencing: a new gallery takes COALESCE(MIN(sort_order), 1) - 1 within its parent group — the COALESCE is required, since a bare MIN returns NULL for the first gallery in an empty group. This preserves today's behavior exactly at O(1) per create, and avoids rewriting every sibling row on every gallery creation. Sibling groups are densely resequenced by explicit placement, so density is guaranteed wherever it matters and the id tiebreak covers the rest. (A deliberate deviation from prepend-at-zero-and-resequence: same observable ordering, without write amplification on the hot create path.)
fn_create_gallery gains an optional parent, which changes its signature. Its existing idempotency-key replay path must be preserved through that change — a retried create still returns the original gallery rather than inserting a second one, and the old overload is dropped explicitly.
ON DELETE SET NULL remains on the FK as a safety backstop only — deletion is an explicit operation (below), not a reliance on cascade behavior. Under CASCADE, deleting a parent would delete its children's rows, and the bucket-key collection in fn_delete_gallery only walks one level — so every image nested below would be removed from the database while its bytes stayed orphaned in the bucket forever.
Deletion
Deleting a parent is an ordered operation, not a bare DELETE:
- Take the per-user structural lock.
- Promote the children to roots, inserting them at the deleted parent's
sort_orderposition and preserving their relative order among themselves. - Densely resequence the root group.
- Delete the parent row, cascading to its own images and returning their bucket keys for storage cleanup, exactly as today.
The client store must reconcile the whole affected group, not just drop the deleted row — the current deleteGallery action filters out the deleted UUID and leaves the rest of the list untouched, which would leave newly-promoted children invisible until a reload.
Canonical ordering and the tree read
Ordering is defined at two levels, and the second does not follow from the first:
- Within a sibling group, rows sort by
(sort_order, id). The trailingidmakes ordering deterministic even if two rows ever share asort_order. - The tree projection emits each ordered root immediately followed by that root's ordered children, then the next root. A flat
ORDER BY parent_id, sort_order, iddoes not produce this — it groups every root together and then every child by database parent id, which is neither display order nor stable across parent renumbering.
Owner-facing DTOs expose parentUuid, never the integer parent_id, consistent with the platform rule that integer identifiers stay internal.
vw_galleries already carries two correlated per-row subqueries (image count and total size); usage_count belongs to vw_gallery_images, not here. The owner tree read must not add more correlated subqueries — child counts and descendant image counts are assembled from grouped aggregates over the owner's rows within the existing single-call read.
The owner tree arrives as one complete ordered response — no per-parent fetch fan-out.
API
One canonical placement command replaces the overlapping PATCH / move / reorder contracts. This matters beyond tidiness: the shared tree hook currently computes a destination index and then persists only the new parent, so a cross-parent drag lands at an arbitrary position. Making position part of the command makes that class of bug unrepresentable.
POST /api/galleries/{uuid}/placement
{
"parentUuid": "uuid or null",
"beforeUuid": "uuid or null"
}
parentUuid: null means root. beforeUuid names the sibling to insert ahead of; null means append to the end of that group. One command covers same-parent reorder and cross-parent movement, and atomically resequences both affected sibling groups.
Placement and deletion both return the complete canonical owner tree. Returning only the mutated row would leave both resequenced sibling groups stale on the client, which is exactly the drift the single-call read exists to prevent.
- Metadata
PATCHstays free of placement.PATCH /api/galleries/{uuid}never acceptsparentUuid— no""-means-root ambiguity, no two paths to the same mutation. - Creation accepts an optional parent.
POST /api/galleriestakesparentUuid; omitted ornullmeans root.
Every existing gallery and image route is otherwise untouched.
Authorization
Three UUIDs can appear in one placement request, and each is resolved and authorized independently — the route's {uuid}, the parentUuid, and the beforeUuid. Every combination has a defined answer: foreign, missing, wrong sibling group, and self-reference.
The shared RequireOwnedGallery helper returns 403 for a gallery owned by someone else, and 404 only when the UUID does not exist at all. Placement inherits that contract. Changing the helper would alter every existing gallery route and is out of scope — the criteria below assert the shipped behavior rather than a non-leaking 404 that does not exist.
The drawer
The gallery drawer is the surface this feature lives or dies on. It is narrow on desktop and narrower on mobile, so the design spends no horizontal space on hierarchy.
Hierarchy on one guide line, in the Forge's list rows
Changed 2026-11-21 (owner: "Make the folders look similar to how forge has entity list in the drawer visually"). Earlier versions conveyed hierarchy by weight alone (a smaller cover and dimmer name, no indentation).
Every row is the Forge's side-list line (the shared CompactRow): one dense row, no card — the drag grip at the left edge
(where a pointer hovers), the chevron column, the cover in a small chip, the name, and at the end one place the picture
count and the row's ⋯ share (the count at rest, the ⋯ on hover, keyboard focus or an open menu). A subfolder takes the
chevron's column as its indent, on a thin guide line under its parent's chevron, so it costs the name column nothing;
root and subfolder rows are the same size.
A parent that has children has a chevron in that column; a top-level gallery without children keeps the column empty so every row stays left-aligned. On a library with no subfolders at all, no chevron column is rendered.
Selection, URL, and expansion state
Management lives on the media site at media.echoofdreams.eu/images (the writing app's old /creator/gallery forwards there, query included). Before this feature it took no parameter — selection lived only in memory, so there was nothing to deep-link to. This feature defines:
/images?gallery={uuid}as the selection contract, kept synchronized as the user selects.- Arriving at a subfolder URL expands its ancestors, so a selection is never invisible behind a collapsed parent.
- An unknown or foreign UUID falls back to All Images — the store's existing default when nothing is selected — with no error state.
Expansion state is not currently persisted by the layout — ThreePanelLayout's storageKey persists the drawer's resizable width only. Expanded gallery UUIDs are therefore stored explicitly: versioned, user-scoped local storage, with stale UUIDs pruned on load so deleted galleries cannot accumulate forever.
Placement and subfolder creation are their own transactions
The gallery settings form is a single Save/Cancel surgical-update form over metadata. Placement is a separate command against a separate endpoint, so folding a location field into that form would make one Save into two requests with undefined partial-failure and dirty-state behavior.
Instead, the metadata form is left unchanged, and two explicit actions sit alongside it:
- Change location — opens a modal that issues the placement command, with its own Cancel / Move pair.
- New subfolder — opens a modal prefilled with the selected gallery as parent, with its own Cancel / Create pair.
Each is one transaction with one outcome. This also draws a distinction the earlier draft blurred: relocating this gallery and creating a child of it are different operations and need different affordances.
Dragging remains available for fast reorganization, but is never the only path — it is unusable by keyboard, hostile on touch, and invisible to assistive technology. The tree exposes semantic roles, supports keyboard expansion and reordering, shows visible focus, and uses touch targets sized for the mobile drawer.
Drag and hold to open
Dragging images onto a collapsed folder needs a way to reach what is inside it. Hovering a drag over a collapsed folder for a moment expands it in place, revealing its subfolders as live drop targets — the creator continues the same drag straight into the subfolder they wanted.
Spring-open state is transient: it never writes to the persisted expansion preference, and it is cleared when the drag ends or is cancelled. It must, however, stay open while the pointer moves from the parent row into the branch it just revealed — collapsing the moment the pointer leaves the parent row would destroy the drop target the gesture exists to reach.
Reusing the tree substrate
useSortableTree in the shared library provides flat-list tree rendering, drop-gap positioning, drag-to-reparent, and client-side cycle prevention. Gallery folders are its second consumer, so the substrate is generalized before the feature is built on top of it, rather than forked:
- Identifier-generic signatures. The hook coerces node identifiers with
Number()throughout; galleries are addressed by UUID. Comparison becomes identifier-agnostic, with the documentation tree's integer nodes regression-checked in the same slice. - Destination placement.
handleDragEndcomputes an insertion index and then calls a move function that takes only a parent. The persisted contract gains the destination, matching the placement command. - Typed drag metadata instead of prefix inference. Drag and drop identity is carried as typed payload rather than inferred from string prefixes, so a page dragging two kinds of thing dispatches on data, not naming convention.
- A
canDrop/ maximum-depth policy hook, so "only roots may have children" is enforced during the drag rather than discovered on rejection. - Active-kind collision handling, so image drags and gallery drags resolve against the right drop targets in one shared context.
- Server-message error propagation, replacing the parameterless
onError, so a rejected placement surfaces the reason. - Opt-in spring-loaded expansion, transient by contract, available to the documentation tree later for free.
Tests cover both consumers: integer documentation nodes and UUID galleries.
The affected flat surfaces
Four surfaces render the user's galleries as a flat list today. All four must become hierarchy-aware, or they flatten children and lose their parent context:
| Surface | Location |
|---|---|
| Gallery drawer | clientConsole gallery page |
| "Move Images" picker | clientConsole image grid |
| Image picker — gallery browsing | shared — used by client and blog consoles |
| Upload destination selector | shared upload panel — used by client and blog consoles |
The durable boundary is not one component rendering every row. A read-only chooser and a drag-sortable drawer have genuinely different jobs, and forcing them into one component would make both worse. Instead:
- A canonical shared gallery-tree type plus a flattening/projection utility — the model all four share.
- A shared
GalleryTreeSelectfor the Move Images picker, image-picker browsing, and upload destinations. - A purpose-built sortable drawer consuming the same model and the same row primitives.
Implementation Plan (Sliced)
| Slice | Scope | Status |
|---|---|---|
| 1 — Shared tree model | Canonical tree type, flattening/projection utility, read-only navigator and select, generic sortable adapter with error propagation, tests for both integer and UUID consumers. | ✅ shipped |
| 2 — Database | Idempotent order-preserving migration, named guarded FK, locking structure trigger, immutable ownership, atomic placement and delete functions, mapped error codes, direct-SQL invariant and concurrency tests under READ COMMITTED. |
✅ shipped |
| 3 — Backend | Canonical shared DTOs (parentUuid), placement endpoint returning the full tree, independent authorization for all three UUIDs, single-call ordered tree read via grouped aggregates, fn_create_gallery idempotency preserved. |
✅ shipped |
| 4 — Owner drawer | Tree rendering, de-emphasised subfolder row, chevron, URL selection contract, Change location and New subfolder modals, versioned expansion persistence, accessibility. | ✅ shipped |
| 5 — Drag and drop | Composed image/gallery drag, transient spring expansion with branch-hold, measuring strategy. | ✅ shipped (code); pointer-drag paths not yet exercised in a browser |
| 6 — Remaining surfaces | Move Images, image-picker browsing, upload destination; both-console regressions; showcase coverage. | ✅ shipped |
| 7 — Future public hierarchy | Blocked. See below. | ⛔ blocked |
Slices 1–6 are the feature, and all six are required — slice 6 is not polish, because without it three of the four gallery surfaces silently flatten the hierarchy.
Future public hierarchy (blocked)
Exposing subfolders to anonymous viewers is not a deferrable tail of this work; it is a separately gated follow-on that must not ship on this feature's gate.
The Anonymous Entry architecture records an open finding: the public gallery endpoint gates solely on is_public, has no maturity gate, and its maxRating is a caller-supplied filter with no server-enforced ceiling — while image content ratings genuinely reach NSFW. That finding is currently classified as accepted risk specifically because a public gallery UUID is never embedded in a crawlable surface — profile enrichment does not reference galleries, and the only OpenGraph gallery touch is a single already-gated project cover.
Linking gallery hierarchy into public discovery is exactly the change that would flip that classification. Three gates must land first:
- Gallery inclusion in the anonymous entity-type allowlist — galleries are not in it today.
- A platform-approved anonymous-exposure flag, distinct from
is_public. Creator intent to list is not the same as platform approval to expose anonymously. - A server-enforced request maturity ceiling, so
maxRatingcannot be raised by the caller.
When it proceeds, it uses a viewer-specific projection — phrased in terms of what is accessible to that viewer, not what is nominally public — followed by a security review:
- Accessible parent + accessible child — nest normally.
- Accessible parent + inaccessible child — omit the child from rows, counts, and chevrons.
- Inaccessible parent + accessible child — promote the child to a visible root, exposing no parent metadata.
- Covers and descendant counts include only nodes and images accessible to that viewer; under-review or above-ceiling images can never surface as a public cover.
Downstream invariant — organization only
Nesting is a presentation and organization relationship. It must not become a traversal rule anywhere else in the system:
Nesting never expands gallery-level entity links, image links, recall-keyword resolution, cover selection, quota, moderation, access, or collaborator authority. Every operation remains scoped to the exact gallery named, unless a child gallery is explicitly linked in its own right.
Structural mutations remain owner-library operations. If project or collaboration permissions later apply to galleries, they evaluate each gallery independently rather than inheriting down the tree.
Open Questions
None outstanding. Recursive deletion — previously open — is resolved as a non-goal: deleting a parent promotes its children and never destroys nested images.
Acceptance Criteria
The feature is not done until every box below is verified ✅ against the running product. Public hierarchy is excluded from this gate; its criteria live with the blocked follow-on.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- UC-1 — As a creator, I can create a subfolder inside a gallery via a New subfolder action prefilled with that gallery as parent, in one Create transaction.
- UC-2 — As a creator, I can relocate an existing gallery via a Change location action, in one Move transaction, without touching its metadata form.
- UC-3 — As a creator, I can see which galleries have subfolders and expand or collapse them from the gallery drawer.
- UC-4 — As a creator, I can drag an existing gallery onto a root gallery to make it a subfolder.
- UC-5 — As a creator, I can drag images onto a collapsed folder, have it open under the held drag, move the pointer into the revealed branch, and drop into a subfolder without restarting the drag.
- UC-6 — As a creator, I can reach a subfolder from the Move Images picker, the image picker in character and lorebook forms, and the upload destination selector — not only from the gallery drawer.
- UC-7 — As a creator, I can reorder galleries within their parent group and the order survives a reload.
- UC-8 — As a creator on a phone, the drawer shows nested galleries without the name column becoming unreadable.
- UC-9 — As a creator using only a keyboard and a screen reader, I can expand, collapse, select, and re-place a gallery, with the hierarchy announced.
- UC-10 — As a creator, I can link directly to a subfolder and arrive with it selected and its parent expanded.
- UC-11 — As a creator, when a placement is rejected I see why ("only top-level galleries can contain subfolders"), not a generic failure.
Behavior (exercise the mechanism):
- Creating a gallery with a
parentUuidplaces it under that parent; omitted ornullplaces it at root. -
POST /api/galleries/{uuid}/placementperforms same-parent reorder and cross-parent movement through the one command. - Placement and deletion each return the complete canonical owner tree, and the client reconciles both resequenced sibling groups from it without a reload.
- Cross-parent placement lands at the exact requested position and survives a reload there.
- The tree response emits each root immediately followed by its own ordered children, and sibling groups sort by
(sort_order, id). - Owner DTOs carry
parentUuid; no integerparent_idreaches the client. -
PATCH /api/galleries/{uuid}does not acceptparentUuid— metadata updates cannot move a gallery. - Existing galleries retain their exact newest-first order after the migration, and a newly created gallery still appears first — including the first gallery created in a previously empty group.
- A retried gallery create with the same idempotency key returns the original gallery, with parent placement in the signature.
- Deleting a parent promotes its children into the parent's former root position, in their prior relative order, and deletes only the parent's own images.
- Expansion state survives a page reload, is scoped to the user, and prunes UUIDs that no longer exist.
- A collapsed folder displays a count of the images held in its descendants.
- Dropping images onto a folder row moves them into that folder, as it does for any gallery today.
- A drag held over a collapsed folder expands it, and a subfolder revealed during that drag accepts the drop.
- The owner tree arrives in one ordered response — no per-parent fetch fan-out.
Invariants that must stay true (carve-outs a reviewer can break if regressed):
- Existing
g://references resolve unchanged. A reference written before this feature, to a gallery that has since become a subfolder, still resolves to the same image — no path segments, no rewrite, no migration. - Gallery slugs remain unique per user, and a subfolder is addressed by its own short slug.
- A root that has children cannot be placed under another root — rejected through the API and through direct SQL.
- Ownership is immutable — a direct
UPDATE galleries SET user_id = ...is rejected, so no cross-owner edge can be introduced without aparent_idchange. - Cross-owner parenting fails through direct SQL as well as through the API.
- Concurrent opposite moves cannot produce a cycle or a non-dense sibling order — verified with concurrent direct-SQL transactions under
READ COMMITTED. - Deleting a parent never deletes a child's images. Children become root galleries; their images and bucket objects survive.
- Structural rejections surface as 409 with the raised message (and 403 for ownership), never as a generic 500.
- No visibility inheritance — a public subfolder under a private parent stays publicly reachable, and a private subfolder under a public parent stays private.
- Storage quota is unchanged — the per-user total counts every image once regardless of nesting depth, and the quota check does not become depth-sensitive.
- Nesting does not recurse entity links, image links, recall-keyword resolution, cover selection, quota, access, or moderation — each remains scoped to the exact gallery named.
- Image operations are untouched — upload, confirm, crop, reorder, move, bulk delete, bulk rating, and entity linking behave exactly as before.
- The admin documentation tree is unchanged by the
useSortableTreegeneralization — reorder, reparent, expand/collapse, and cycle prevention all still work. - The public gallery page is unchanged — no hierarchy, no subfolder listing, no new fields reach an anonymous viewer.
- Unsorted stays pinned at root and can be neither nested nor nested into.
- Admin moderation is unaffected — the gallery image tables, filters, and bulk actions behave identically.
- A library with no subfolders is visually unchanged — same initial order, layout, spacing, row height, and chrome as today, with no chevron column and no hierarchy spacer. (URL synchronization, DTO shape, and drag behavior change deliberately and are out of this invariant's scope.)
- Spring-open state is transient — a drag never mutates the persisted expansion preference.
- Both consoles regress clean — the shared picker and upload panel preserve parent context in the client and blog consoles.
Edges (empty / failure / unauthorized / boundary):
- Making a gallery its own parent is rejected, with a readable message and no partial write.
- A placement that would exceed two levels is rejected with a message naming the limit, from both the drag interaction (prevented before drop) and the API.
- A foreign gallery in the route position returns 403; a foreign
parentUuidand a foreignbeforeUuidare each rejected independently. - A placement naming a non-existent parent returns not-found and leaves the gallery where it was.
- A
beforeUuidnaming a gallery in a different parent group is rejected rather than silently appended. - An empty folder — no images, no children — renders without a chevron and is still selectable and droppable.
- Cancelling a drag that spring-opened a folder leaves no half-applied move and no persisted expansion change.
- A deep link to an unknown or foreign gallery UUID falls back to All Images, without an error state.
- A library large enough to be realistic (hundreds of galleries) renders and drags without visible lag.
Related documents
- Gallery & Image Storage — the shipped gallery system this extends, and the source of the flat-list decision reversed here.