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

Non-Goals

Deliberately out of scope — several of these a reader would reasonably assume are in:

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.

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:

  1. Rejects any user_id change on update — ownership is immutable after insertion. Without this, a direct UPDATE galleries SET user_id = ... creates a cross-owner edge without ever firing a parent_id trigger. The one exception is an account merge: it sets the transaction-local eod.gallery_owner_transfer to 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.
  2. 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.
  3. 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:

  1. Take the per-user structural lock.
  2. Promote the children to roots, inserting them at the deleted parent's sort_order position and preserving their relative order among themselves.
  3. Densely resequence the root group.
  4. 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:

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.

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:

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:

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:

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:

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:

  1. Gallery inclusion in the anonymous entity-type allowlist — galleries are not in it today.
  2. A platform-approved anonymous-exposure flag, distinct from is_public. Creator intent to list is not the same as platform approval to expose anonymously.
  3. A server-enforced request maturity ceiling, so maxRating cannot 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:

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):

Behavior (exercise the mechanism):

Invariants that must stay true (carve-outs a reviewer can break if regressed):

Edges (empty / failure / unauthorized / boundary):