Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

19.6 KB
Raw Blame

Product Media System

Status: In Progress — 5.4 and 5.5 in; 6.0 Phases 1–4 implemented 2026-08-18: video support (hosted + external), focal point, the Asset → Media rename, and cleanup. Target: Spree 5.4 (foundation) + Spree 5.5 (data model + product gallery UI) + Spree 6.0 (video, rename, cleanup) Depends on: 6.0-remove-master-variant.md (shipped — master is already gone, so the 6.0 re-homing phase below is inherited rather than owned) Author: Damian + Claude Last updated: 2026-08-18

Summary

Spree's image system ties each Spree::Image 1:1 to a Spree::Variant. Sharing an image across variants requires re-uploading it, duplicating Active Storage blobs. There is no product-level media gallery, no video support, and no focal point for smart cropping.

This plan moves to a product-level media gallery (the industry standard) where variants reference product media via a join table. Blobs are never duplicated. The Store API renames images → media with a media_type discriminator.

Key Decisions (do not deviate without discussion)

  1. Rename images → media throughout the Store API. Clean break — no deprecated alias.
  2. Drop viewable_id/viewable_type from Store API. Admin API keeps them.
  3. Add product_id to the media serializer.
  4. One media class, no STI — Spree::Image logic was merged into the single media class in 5.4. Spree::Image survived 5.4/5.5 as a thin subclass for backward compatibility and is removed in 6.0 (see decision 8).
  5. media_type defaults to 'image' — always present, never null.
  6. No dedicated Store media endpoint — media is served via expand=media on products/variants (industry standard).
  7. VariantMedia join table lands in 5.5 — enables variants to reference product-level assets without duplicating blobs. Direct variant images association stays for backward compatibility. The join is internal plumbing, not an API surface: callers manage variant assignment via PATCH /products/:id/media/:asset_id { variant_ids: [...] } (the Spree::Asset#variant_ids= setter resolves prefixed IDs and enforces same-product). Named VariantMedia (table spree_variant_media) — matches the industry convention (Shopify, Vendure, BigCommerce all expose a variant_media or productVariantMedia join concept).
  8. Rename Spree::Asset → Spree::Media in 6.0 — aligns model/table/prefix with API naming. Spree::Asset stays readable one release as a deprecated alias; Spree::Image goes.
  9. Product is the default upload target — POST /api/v3/admin/products/:id/media attaches to Spree::Product directly. Variant-pinned images keep displaying via gallery_media until merchants run the migration rake.
  10. Both hosted and external video ship in 6.0 (2026-08-18). video means an uploaded file and requires an attachment; external_video means a YouTube or Vimeo link and requires a URL. The two are distinct media_type values, never one field doing both jobs.
  11. Spree parses the video URL once, at the API boundary. The serializer exposes the provider and an embeddable URL so every headless storefront doesn't re-implement YouTube and Vimeo link parsing. Spree stores what the merchant typed and derives the rest.
  12. Hosted video carries a poster image. A gallery that only knows how to draw an <img> still renders a sensible still, and the storefront chooses when to load the video itself.
  13. media_type is the discriminator, never the STI type column. inheritance_column is nil; any write path keying off type is a bug.

Design Details

Data Model

Spree::Media (6.0 rename of Spree::Asset; Spree::Image removed)
  viewable_type: 'Spree::Product' (default) or 'Spree::Variant' (legacy)
  media_type:    'image' | 'video' | 'external_video' (default: 'image')
  focal_point_x, focal_point_y (decimal, nullable)
  external_video_url (string, nullable)

  image          → attachment required (image content types), no URL
  video          → attachment required (video content types), no URL,
                   poster image derived for gallery display
  external_video → external_video_url required, no attachment;
                   provider + embed URL derived at the API boundary

Spree::Product
  has_many :media, as: :viewable           ← product-level gallery
  has_many :variant_images, through: ...   ← kept for backward compat
  #gallery_media → media.any? ? media : variant_images

Spree::Variant
  has_many :images, as: :viewable          ← kept (direct variant uploads)
  has_many :variant_media                  ← 5.5: links to product-level Assets
  has_many :associated_media, through: :variant_media, source: :asset
  #gallery_media → associated_media (if any) else images

Spree::VariantMedia (5.5, table: spree_variant_media)
  belongs_to :variant
  belongs_to :asset (FK: media_id, points at spree_assets in 5.5 / spree_media in 6.0)
  unique index on [variant_id, media_id]
  no position column — gallery order comes from the asset's product-level position

Store API (5.4)

Field Type Notes
id string Prefixed ID (media_xxx)
product_id string | null Product prefixed ID
media_type string 'image', 'video', 'external_video'
position number Sort order
alt string | null Alt text
focal_point_x number | null 0.0–1.0
focal_point_y number | null 0.0–1.0
external_video_url string | null YouTube/Vimeo URL as the merchant entered it
video_provider string | null 'youtube', 'vimeo' — derived, 6.0
video_embed_url string | null Embeddable player URL — derived, 6.0
video_url string | null Hosted video file URL — 6.0
poster_url string | null Still frame for a video tile — 6.0
original_url string | null Full-size image URL (null on video)
mini_url ... xlarge_url string | null Named variant URLs (null on external video)

Removed from Store API: viewable_id, viewable_type Admin API extends Store with: viewable_id, viewable_type

Breaking Changes (5.4)

Change Before After
Expansion param expand=images expand=media
Response key "images": [...] "media": [...]
viewable_id Present Removed (Store API)
viewable_type Present Removed (Store API)
TS type Image / StoreImage Media / StoreMedia
Serializer ImageSerializer MediaSerializer (deleted, no alias)

Migration Path

5.4 (PR #13778) — DONE ✓

  • New columns on spree_assets: media_type, focal_point_x/y, external_video_url
  • Backfill existing records: media_type = 'image'
  • Merge Spree::Image into Spree::Asset
  • Store API: MediaSerializer replaces ImageSerializer, expand=media
  • Admin API: Admin::MediaSerializer extends Store (adds viewable_id/type)
  • SDK bumped to 0.11.0, Next bumped to 0.11.0
  • TypeScript types, Zod schemas, OpenAPI spec regenerated
  • Docs updated throughout

5.5 — SHIPPED ✓

5.5 delivered the data model, the API and the product gallery UI. Variant-level media keeps working unchanged. The data-migration rake shipped opt-in so existing merchants choose when to re-home variant-pinned images.

Phase 1: VariantMedia join table — shipped

  • spree_variant_media table + Spree::VariantMedia model, unique index on [variant_id, media_id], no position column (order inherits from the asset's product-level position)
  • Variant#variant_media, Variant#associated_media, Variant#gallery_media preferring the join over direct images
  • VariantMedia.resolve_variant_ids is the security boundary — variants from another product are dropped

Phase 2: Admin API — Product is the default parent — shipped

  • POST /api/v3/admin/products/:product_id/media defaults to viewable_type: 'Spree::Product'; the variant_id path still creates variant-pinned assets
  • Variant assignment travels as variant_ids on the media endpoint — no dedicated link/unlink routes
  • Product-scoped listings union product-level assets with any still pinned to the default variant, so legacy data keeps rendering
  • Inline media: [...] on the product PATCH upserts by id and creates from signed_id

Phase 3: Legacy Rails admin — dropped, not shipped The spree/admin engine was removed from the monorepo entirely (commit 464df815f2). There is no legacy admin form to retarget, so this phase no longer exists.

Phase 4: Admin SPA UI — partially shipped

  • Product gallery card: drag-and-drop upload, drag-to-reorder, delete, an edit sheet for alt text and variant assignment. Form-backed — everything except delete rides the parent product save.
  • Not shipped: the focal-point picker (delivered by 6.0 below), and the variant "select from product gallery" flow — VariantMediaPicker was written but never mounted anywhere. It is deleted in 6.0, not finished: assignment is a property of the media row (variant_ids), edited from the product gallery, so a second variant-side picker was a duplicate surface for the same data.

Phase 5: Data migration rake — shipped

  • spree:media:migrate_master_images_to_product_media enqueues Spree::Media::MigrateProductAssetsJob per affected product; idempotent, opt-in, BATCH_SIZE env
  • spree:media:backfill_primary_media backfills primary_media_id

6.0 — IN PROGRESS

Master variant is already gone (6.0-remove-master-variant.md shipped), so re-homing is no longer this plan's job — the media rake is listed as a prerequisite by remove_master_variant.rake and merchants run it as part of that upgrade. What remains here is video, focal point, the rename and the cleanup.

Phase 1: Video support — shipped 2026-08-18

The 5.5 columns advertised video that nothing could create. media_type is read-only on every write path — permitted_params in media_controller.rb and the inline media: list in products_controller.rb permit neither media_type nor external_video_url nor the focal point. Both write paths also route creation through the dead STI type column, defaulting to 'Spree::Image'.

Spree ships both hosted and external video (2026-08-18 decision) — merchants arrive with footage in both shapes, so supporting one and not the other pushes half of them to a workaround. What landed:

  • media_type: 'video' — a file uploaded through Active Storage. Requires an attachment, not a URL (the 5.5 validation had this backwards and is fixed).
  • media_type: 'external_video' — a YouTube or Vimeo URL. Requires external_video_url, has no attachment.
  • Validation is type-directed: image → attached image; video → attached video (Spree::Config.video_content_types + max_video_upload_size); external_video → a URL Spree recognises.
  • Spree::ExternalVideo is the value object that reads a link — provider, video id, embed URL, watch URL, provider thumbnail. It rejects non-video and non-http URLs, and the dashboard mirrors it in lib/video-url.ts so a merchant learns a link is unusable while typing.
  • The serializer exposes video_provider, video_embed_url, video_url and poster_url. A video's sized URLs (small_url …) resolve to its poster, so an image-only gallery still renders.
  • Video carries an optional poster attachment (poster_signed_id on write, uploadable from the media editor); YouTube falls back to its own thumbnail. Spree does not extract a frame from an uploaded file — that needs ffmpeg in the deployment image, and the two comparable self-hosted platforms ship neither video posters nor the dependency (2026-08-18 research). Active Storage's VideoPreviewer degrades silently without ffmpeg, so it stays available as an additive step for merchants who install it.
  • Write paths: media_type, external_video_url, poster_signed_id and the focal point are permitted on both the media controller and the inline product media: list. Creation keys off media_type; the STI type param is gone.
  • Dashboard: video files upload through the same drop zone, an "Add video" dialog takes a link, video tiles carry a play badge, and the edit sheet plays the video (iframe for external, <video> for hosted).

Phase 2: Focal point + variant picker (the 5.5 UI remainder)

  • Shipped: focal-point picker — click the image in the media edit sheet to place the point, with a marker and a reset. Writes focal_point_x/y through both write paths.
  • Shipped: deleted the never-mounted VariantMediaPicker, its use-variant-media hook and their locale keys. Media is unified on the product, and the media edit sheet already picks which variants use a given item — a variant-side picker would be a second way to edit the same variant_ids. The variant-scoped API endpoints and SDK methods stay: direct variant uploads remain a supported path and existing merchant data depends on them.

Phase 3: Rename Asset → Media — shipped 2026-08-18

  • spree_assets → spree_media, Spree::Asset → Spree::Media
  • Spree::Asset is a deprecated constant alias for one release; Spree::Image is gone. The :asset and :image factories stay as aliases of :media.
  • spree:migrate_media_class_names rewrites the stored class names (custom field resource types, extension polymorphic columns) and is in the 5.6→6.0 manifest, along with the previously unlisted spree:media:migrate_master_images_to_product_media — which must run before spree:remove_master_variant, or deleting a ghost master takes its media with it.
  • Spree::Api::V3::AssetSerializer → MediaEventSerializer (the lean event payload). Media pins it explicitly, since name-convention resolution would otherwise pick the full customer-facing MediaSerializer.
  • Fixed on the way: the 5.5 AddProductMediaSupport migration called Spree::Asset to backfill, so after the rename it looked for a table that did not exist yet. It uses raw SQL now.

Phase 4: Cleanup

  • Shipped: removed Asset.styles / default_style and the Support::ActiveStorage module behind them — nothing called url(style) anywhere in the monorepo.
  • Shipped: dashboard copy reworded for a mixed gallery, in all six locales.
  • Shipped: Variant#secondary_image, Product#secondary_image and Variant#additional_images are deprecated, removed in 6.1. Nothing in Spree called any of them — no serializer, no API, no dashboard code — and which image to show on hover, or beside the main one, is a storefront presentation choice rather than something core should name. All three shells now read gallery_media, which also fixes the bug they shared: reading images (and, for additional_images, product.images, itself a delegate to the default variant) returned nothing for a variant whose gallery comes from linked product-level media.
  • Still open: remove Product#variant_images — a live fallback while merchants run the migration rake, so it goes when the legacy path does.

Constraints on Current Work

  • Always use expand=media (not expand=images) in new Store API code and SDK examples
  • Use Spree::Media in new code once the rename lands; Spree::Asset reads as a deprecated alias for one release and Spree::Image is gone
  • Use gallery_media as the unified accessor on Product and Variant — never variant_images directly
  • Default new product-level uploads to viewable_type: 'Spree::Product' — never pin new uploads to a variant
  • Variant-level direct uploads stay valid via viewable_type: 'Spree::Variant'. Prefer VariantMedia rows linking to product-level assets when sharing a blob across variants
  • media_type is never null — defaults to 'image', always validate inclusion
  • Never branch on the STI type column. media_type is the discriminator; inheritance_column is nil and type is a vestige awaiting removal
  • A new media attribute must be permitted in two places or it is silently dropped on one write path — MediaController#permitted_params AND the inline media: [...] list on Admin::ProductsController. The dashboard's product Save hits the second one, so a spec on the media controller proves nothing about it
  • Never assume a media row has an attachment. External video has none; any code calling attachment, original_url or a size variant must handle a video row
  • Do not run the media migration rake automatically on upgrade — it stays opt-in, and remove_master_variant.rake names it as a prerequisite

Scope Boundary: Merchandising Media, Not a DAM

Spree::Asset (renamed Spree::Media in 6.0) is merchandising media for commerce entities — product photography, variant shots, swatches, eventually category/brand hero images. It is intentionally not a general-purpose Digital Asset Management system.

Storytelling, editorial content, blog posts, landing-page copy, lifestyle imagery, marketing collateral — none of this is Spree's job in a headless world. Headless storefronts pair Spree with a CMS (Payload, Sanity, Strapi, Hygraph, etc.) and that CMS owns its own asset library. Spree's role is to expose CDN URLs the storefront consumes; everything upstream of that URL is somebody else's surface.

Implications:

  • No "Files" page in admin. No central library, no cross-entity picker, no tag taxonomy, no "where is this used" reverse lookup, no bulk replace. Each commerce entity owns its own gallery via the polymorphic viewable association.
  • Active Storage already deduplicates blobs by checksum — uploading the same file twice creates two cheap Asset rows pointing at one S3 object. The economic case for a shared library is weak; the UX case in pure-commerce admin doesn't materialize until file counts get huge, at which point the merchant should be on a real DAM (Cloudinary MAM, Bynder, Brandfolder) feeding URLs into Spree.
  • Polymorphism stays narrow. viewable_type extends to commerce entities only — Product, Variant, eventually Taxon if a real customer ask lands. Adding viewable_type: 'Spree::Post' or 'Spree::Page' would imply Spree is a CMS; we don't go there.
  • Storage abstraction is the escape hatch. Merchants needing a real DAM configure a custom storage service (or a Spree.cdn_host) that points at their managed asset platform. The platform owns curation; Spree owns the URL contract.

If a future request asks for cross-entity sharing inside Spree (e.g., "this hero shot belongs to both a Product and the Taxon it's on"), revisit this boundary deliberately — don't drift into it. The default answer remains: no shared library, scope to commerce entities, defer broader media management to upstream tools.

Open Questions

  • Should 3D model support (GLB/USDZ) be a media_type value or a separate system? Deferred — no customer ask yet, and the answer likely mirrors whatever video settles into.
  • Should Spree transcode uploaded video, or serve the original file as uploaded? 6.0 serves the original; transcoding is an infrastructure concern that belongs with a provider, not in core.

Resolved

  • Hosted video uploads as well as external URLs? Yes — both, decided 2026-08-18. See Key Decision 10.
  • Focal point: visual picker or numeric fields? A visual picker. Numeric decimals between 0 and 1 are not something a merchant should be asked to reason about.

References

  • PR #13778: Product media system: core data model + Store API
  • Key files:
    • core/app/models/spree/asset.rb — single Asset class with all media logic
    • core/app/models/spree/image.rb — thin backward-compat subclass
    • api/app/serializers/spree/api/v3/media_serializer.rb — Store API
    • api/app/serializers/spree/api/v3/admin/media_serializer.rb — Admin API