DEV Community

Cover image for Building a Metal-Aware Charm Builder on Shopify Without an App
Sarthak Chatterjee
Sarthak Chatterjee

Posted on Edited on

Building a Metal-Aware Charm Builder on Shopify Without an App

How I built a two-step "build your own necklace" experience for jewellery brand using native Shopify theme code: Liquid, vanilla web components and the Ajax Cart API.


The brief

Jewellery brands often sell personalised jewellery. One of their top requests was a charm builder: a page where a shopper picks a chain, then adds charms to it, and the whole necklace goes to the cart as one bundle.

It sounds simple. The requirements were not:

  1. Two ordered steps. Step 1 is the chain (exactly one). Step 2 is the charms (up to a configurable limit).
  2. Metals must match. If you pick a gold chain, you can only add gold charms. A silver-only charm should still be visible, but clearly marked as unavailable.
  3. Charm order matters. The workshop needs to know which charm goes in which position on the chain.
  4. The bundle must behave as a bundle in the cart. Removing one piece from the cart drawer should remove the whole necklace. It should never leave an orphaned chain or a pile of loose charms behind.
  5. A tiered promo. "Add one more charm to unlock X% off", with live subtotal and strike-through pricing.
  6. Reusable. Marketing wanted the same builder for other launches: Layers of Love, Birthstone Spacer, Birth Flower, Initial Script and Oval Birthstone pages, each with its own products, copy and imagery.
  7. Merchant-editable. Everything (steps, tabs, limits, copy, promo thresholds, banners) had to be controllable from the theme editor.

The rules (metal matching, slot positions, group removal) are specific to how this brand makes jewellery. That pointed us towards a custom build inside the theme instead of bending a generic bundle app to fit.


Architecture at a glance

The builder is a single theme section, bundle-builder.liquid. It renders the static shell and product data, then a small set of ES modules adds the interactive behaviour on top.

sections/bundle-builder.liquid
 ├─ Liquid: layout shell, tabs, progress bar, sidebar, settings → JSON config
 ├─ snippets/bundle-builder-*-json.liquid → <script type="application/json"> product data per tab
 ├─ <script type="importmap"> → maps @bundle-builder/* to CDN asset URLs
 └─ <script type="module" src="section-bundle-builder.js">
        │
        └─ <bundle-builder> custom element (the "host": state + orchestration)
             ├─ @bundle-builder/utils          money, metal detection, cart payloads
             ├─ @bundle-builder/grid           card hydration, metal filter, "show more"
             ├─ @bundle-builder/sidebar        bundle summary, subtotal, promo copy
             ├─ @bundle-builder/quick-view     product modal + carousel
             ├─ @bundle-builder/product-actions  ADD / qty / UNAVAILABLE button HTML
             └─ @bundle-builder/drag-scroll    drag-to-scroll tab strip

assets/component-bundle-builder-cart.js  (site-wide) → "remove one, remove all" in the cart drawer
Enter fullscreen mode Exit fullscreen mode

There's roughly 5,500 lines across Liquid, JS and CSS. One design decision shaped all of it:

Only <bundle-builder> is a custom element. Everything inside it is plain markup with data-* hooks, and the submodules export functions and not classes.

The host owns all state (chain, charms, metalFilter, uiStep). The submodules are stateless renderers that receive the host as an argument. That keeps one source of truth and makes the data flow easy to follow.


1. Data: Liquid → JSON → JS

Each tab in the builder is a section block. There are three block types:

Block Use
bundle_collection All products from a collection
bundle_product A single product (e.g. one specific chain)
bundle_product_list A hand-picked list of products

Each block has a step setting (1 or 2) and a tab title. Blocks render in the order the merchant arranges them in the theme editor.

Product data is serialised server-side into JSON script tags, so the first paint needs no API calls:

{% paginate col.products by 250 %}
  <script type="application/json"
          data-bundle-products="{{ block_id }}"
          data-bundle-step="{{ step }}">
    [
    {%- for product in col.products -%}
      {{- product | json -}}{%- unless forloop.last -%},{%- endunless -%}
    {%- endfor -%}
    ]
  </script>
{% endpaginate %}
Enter fullscreen mode Exit fullscreen mode

Edge case: product lists. Liquid's all_products[handle] lookup is capped at 20 handles per page. Beyond that, some rows come through "thin" (a handle without variants or images). On the JS side, normalizeBundleProductEntry() turns bare handles into { handle } objects. ensureGridProduct() then fetches /products/{handle}.js for any row still missing data. Cards that still have no id after the fetch are skipped, so the grid never renders a broken data-product-id="undefined" card.

Gotcha: {% render %} can't return variables to its parent. We had to keep the product-resolution logic inline in each JSON snippet instead of factoring it into a shared child snippet.


2. Loading modules on Shopify's CDN: use an import map

Our first modular split used relative imports (import … from './component-bundle-builder-grid.js'). It worked locally, then failed in production.

Shopify serves assets from its CDN with a ?v= cache-busting query string. A relative import resolved from inside a module doesn't carry that version, and in our case the child requests 404'd. A failed module import kills the whole module graph. The page then showed only the static Liquid shell: tabs and progress bar present, grids and sidebar empty.

The fix was an import map whose bare specifiers point at the fully versioned asset_url:

<script type="importmap">
  {
    "imports": {
      "@bundle-builder/utils":           {{ 'section-bundle-builder-utils.js' | asset_url | json }},
      "@bundle-builder/product-actions": {{ 'component-bundle-builder-product-actions.js' | asset_url | json }},
      "@bundle-builder/drag-scroll":     {{ 'component-bundle-builder-drag-scroll.js' | asset_url | json }},
      "@bundle-builder/grid":            {{ 'component-bundle-builder-grid.js' | asset_url | json }},
      "@bundle-builder/sidebar":         {{ 'component-bundle-builder-sidebar.js' | asset_url | json }},
      "@bundle-builder/quick-view":      {{ 'component-bundle-builder-quick-view.js' | asset_url | json }}
    }
  }
</script>
<script src="{{ 'section-bundle-builder.js' | asset_url }}" type="module"></script>
Enter fullscreen mode Exit fullscreen mode
// section-bundle-builder.js
import { buildBundleCartItems, detectMetalFromVariantTitle } from '@bundle-builder/utils';
import { hydrateBundleGrids, refreshGridsBundleState, applyStep2MetalFilter } from '@bundle-builder/grid';
import { renderBundleSidebar, renderBundlePromo } from '@bundle-builder/sidebar';
Enter fullscreen mode Exit fullscreen mode

Each asset now gets its own versioned URL, and cache invalidation works correctly on every deploy. Deployment rule: all seven JS files ship together. One missing file breaks the whole import graph.


3. The metal-matching rule

This is the core business rule. When a shopper picks a chain, we read the metal from the chain variant title:

export const BUNDLE_METAL_TOKENS = ['gold', 'silver'];

export function detectMetalFromVariantTitle(title) {
  if (!title) return '';
  const lower = String(title).toLowerCase();
  for (const token of BUNDLE_METAL_TOKENS) {
    if (new RegExp(`\\b${token}\\b`, 'i').test(lower)) return token;
  }
  return '';
}

export function filterVariantsByMetal(variants, metal) {
  if (!Array.isArray(variants)) return [];
  if (!metal) return variants;
  return variants.filter((v) => new RegExp(`\\b${metal}\\b`, 'i').test(v?.title || ''));
}
Enter fullscreen mode Exit fullscreen mode

The word-boundary match is deliberate. "Gold-Filled", "Rose Gold" and "Gold Vermeil" all resolve to gold, and nothing accidentally matches inside an unrelated word. It also means the merchant manages metals the way they already do, through variant names, with no new metafield to keep in sync. Adding a new metal is a one-line change to BUNDLE_METAL_TOKENS.

When the chain is added, the host stores the token and walks every Step 2 card across all tabs:

_addChain(product, variantId) {
  const v = product.variants?.find((x) => x.id === variantId);
  if (!v || !variantAvailable(v)) return;
  this.chain = { productId: product.id, variantId, title: product.title,
                 variantTitle: v.title, price: v.price, image: variantFeaturedSrc(v, product),
                 lineId: uuid() };
  this.metalFilter = detectMetalFromVariantTitle(v.title);
  applyStep2MetalFilter(this);
  this._goToStep2();
  renderBundleSidebar(this);
  this._updateATC();
}
Enter fullscreen mode Exit fullscreen mode

For each card, applyMetalFilterToCard either:

  • rebuilds the variant <select> with only matching variants, keeping the shopper's current choice if it's still valid and otherwise falling back to the first available match; or
  • switches the card to an unavailable state when no variant matches: data-metal-unavailable="true", the select is hidden, an italic "Product not available in gold" notice appears, and the action button becomes a disabled UNAVAILABLE button.

We keep non-matching products in the grid on purpose, so shoppers can see the full range and understand why something can't be added. The message and button text are section settings. The message supports a {metal} placeholder.

The quick-view modal applies the same filter, so you can't sneak a silver charm onto a gold chain through the modal.

A bug we hit: after every add or remove, renderCardBundleState() re-renders each card's action area (ADD button, quantity stepper). It was silently overwriting the UNAVAILABLE button. The fix is an early return for cards flagged data-metal-unavailable. The flag is the single source of truth until the chain is removed.

Clearing the chain (removing it, or jumping back to Step 1 from the progress bar) resets metalFilter to '', empties the charms and re-runs the filter, which restores every variant.


4. State and rendering: avoiding the Safari flicker

The first version did the obvious thing: on every state change, rebuild the grid with innerHTML. In Safari this caused a visible image blink on every click. Destroying and recreating <img> nodes makes the browser repaint (and sometimes re-decode) every image.

We split rendering into two paths:

Function When What it touches
hydrateBundleGrids() First paint only (connectedCallback) Builds all cards
refreshGridsBundleState() Every add/remove Only [data-card-actions] and price rows on existing cards

All state changes go through one method on the host:

_notifyStateChanged() {
  refreshGridsBundleState(this);
  renderBundleSidebar(this);
  if (this._qvContext) renderQuickModalActions(this);
}
Enter fullscreen mode Exit fullscreen mode

The sidebar had the same problem, because its line items include thumbnails. We replaced "clear and rebuild" with a small, signature-based keyed update:

function sidebarLineSignature(row) {
  if (row.type === 'ph') return `ph:${row.text}`;
  const it = row.item;
  return `item:${it.lineId}|${it.variantId}|${it.price}|${it.title}\n${it.variantTitle}|${it.image || ''}`;
}

function syncSidebarLineElements(ul, rows, bundle) {
  for (let i = 0; i < rows.length; i++) {
    const sig = sidebarLineSignature(rows[i]);
    const existing = ul.children[i];
    if (existing?.getAttribute('data-bundle-line-sig') === sig) continue; // keep the node
    const li = createSidebarLineLi(bundle, rows[i]);
    existing ? ul.replaceChild(li, existing) : ul.appendChild(li);
  }
  while (ul.children.length > rows.length) ul.removeChild(ul.lastElementChild);
}
Enter fullscreen mode Exit fullscreen mode

Unchanged rows keep their DOM nodes, and therefore their images. Remove buttons use a single delegated listener on the list instead of being re-bound on every row.

The sidebar always shows a fixed number of slots (max_bundle_items, default 6). Empty slots display merchant-defined placeholder labels ("Select chain", "Charm 1", …), so the shopper can see how much space is left. A counter shows (n/max).

A small CSS trap: the subtotal row uses display: flex, which overrides the browser's built-in [hidden] style. Setting el.hidden = true did nothing until we added:

.bundle-builder__aside-subtotal[hidden] { display: none !important; }
Enter fullscreen mode Exit fullscreen mode

5. Limits, promo and pricing

Two settings cap the bundle: max_bundle_items (chain plus charms) and max_step2_charms. Both are checked before every add.

The promo works off two settings:

  • discount_min_charms sets the threshold for the "add one more" and "unlocked" messages.
  • discount_percent controls whether the subtotal shows a struck-through original price plus a discounted total.
_totalCents() {
  let t = (this.chain?.price || 0) + this.charms.reduce((s, c) => s + c.price, 0);
  const minCharms = this.cfg.discount_min_charms || 2;
  const pct = this.cfg.discount_percent || 0;
  return this.charms.length >= minCharms && pct > 0 ? Math.round(t * (1 - pct / 100)) : t;
}
Enter fullscreen mode Exit fullscreen mode

The messages still render when discount_percent is 0, so merchants can use milestone copy without promising a price change.

⚠️ Note: this is display-side pricing only. The builder sends no discount to the cart, so the price charged at checkout comes from the store's own discount setup. The two have to be kept in sync. Moving this to a Shopify Discount Function that reads the bundle line properties would remove that dependency.

The add-to-cart button is disabled until there's a chain and at least one charm. Its label shows the live total (ADD TO CART | $84.00). While the request is in flight it switches to a loading-dots state with aria-busy="true".


6. Getting the bundle into the cart

Shopify has no native "this group of lines is one product" concept in the Online Store cart (outside of Bundles apps and Cart Transform functions). We model the bundle with line item properties:

export function buildBundleCartItems(bundle) {
  const bundleGroup = String(Date.now());               // one ID per add-to-cart
  const title = (bundle.cfg.cart_bundle_title || 'Charm Builder Bundle').trim();
  const locationPrefix = (bundle.cfg.cart_location_prefix || 'Charm').trim();
  const groupProps = { '_Bundle Group': bundleGroup, '_Bundle Id': bundleGroup, 'Bundle Id': bundleGroup };
  const items = [];

  if (bundle.chain) {
    items.push({ id: bundle.chain.variantId, quantity: 1,
                 properties: { 'Bundle Title': title, ...groupProps } });
  }

  const charmMap = new Map();
  bundle.charms.forEach((charm, index) => {
    if (charmMap.has(charm.variantId)) {
      charmMap.get(charm.variantId).quantity += 1;
    } else {
      charmMap.set(charm.variantId, {
        id: charm.variantId, quantity: 1,
        properties: { 'Bundle Title': title, Location: `${locationPrefix} ${index + 1}`, ...groupProps },
      });
    }
  });

  return [...items, ...charmMap.values()];
}
Enter fullscreen mode Exit fullscreen mode

What each property does:

Property Visible? Purpose
Bundle Title Yes Tells the shopper (and the order) which lines belong to the builder
Location Yes Charm position on the chain (Charm 1, Charm 2, …) for fulfilment
_Bundle Group No (underscore prefix) Timestamp shared by every line in this add-to-cart, the join key for removal
_Bundle Id / Bundle Id No Legacy aliases kept for older cart lines

Because _Bundle Group is created fresh on each add, two necklaces in the same cart stay independent, even though they share the same Bundle Title.

All lines go in a single /cart/add.js request (through Liquid Ajax Cart when it's present, otherwise plain fetch), so the bundle is added as one unit.


7. "Remove one, remove all" in the cart drawer

This was the hardest part. The cart drawer is powered by Liquid Ajax Cart, which binds its own click handlers to remove links and quantity-minus buttons. We needed to intercept those clicks for bundle lines without forking the library.

Step 1: get there first. A capture-phase listener on document runs before the library's bubble-phase handlers:

document.addEventListener('click', onCartClickCapture, true);
Enter fullscreen mode Exit fullscreen mode

Step 2: decide synchronously. Inside the handler we read window.liquidAjaxCart.cart, which is already in memory, so there's no network delay before we have to call preventDefault(). If the clicked line has a _Bundle Group, and that group has more than one line, we take over:

event.preventDefault();
event.stopImmediatePropagation();
Enter fullscreen mode Exit fullscreen mode

A quantity-minus click on a line with quantity > 1 is allowed through, so shoppers can still reduce a duplicated charm.

Step 3: remove the lines one at a time, re-reading the cart after each. This is where most of the debugging went:

async function removeWholeBundle(groupKey) {
  for (let i = 0; i < 30; i += 1) {                 // hard cap, never loop forever
    const cart = await fetchCart();                   // fresh /cart.js every time
    const lines = findBundleLines(cart, groupKey);
    if (lines.length === 0) break;
    const target = lines[lines.length - 1];           // remove from the end
    await postCartChange(target.key);                 // POST /cart/change.js { id, quantity: 0 }
  }
}
Enter fullscreen mode Exit fullscreen mode

Why not something simpler?

  • Not liquidAjaxCart.change() in a loop. When given FormData, the library adds a sections= field to the request body, which affected later calls in our loop.
  • Not one stored list of line keys. Shopify line keys can shuffle after a change if lines re-merge. Reusing a stale key returns 400: no valid id or line parameter. Re-reading /cart.js before each removal guarantees a valid key.
  • Not /cart/update.js with sparse arrays or key maps. It returned 422 errors in this setup.
  • Not cancelling the library's request via requestState.info.cancel = true. The library still fires request-end, and its own handler crashes reading responseData.body of null.

Step 4: show the loading state, then refresh once. While the loop runs, every line in the bundle gets data-loading="true" and aria-busy="true". This reuses the drawer's existing spinner and dims the lines. A module-level bundleRemovalBusy flag swallows extra clicks. When the loop finishes, a single liquidAjaxCart.update({}, {}) re-renders the drawer.

Scoping rule: sibling lines are matched strictly by _Bundle Group. An early version fell back to matching on Bundle Title, and with two necklaces in the cart, removing one removed both.


8. Making it reusable across launches

Because everything is driven by section blocks and settings, a new builder page is a new JSON template, not new code. The same section now powers six templates:

  • page.ee-charm-builder.json
  • page.ee-love-charm.json (Layers of Love)
  • page.ee-birthstone-spacer-builder.json
  • page.ee-birth-flower.json
  • page.ee-initial-script.json
  • page.ee-oval-birthstone-charm.json

The section exposes around 67 settings: limits, cart property labels, promo thresholds, slot labels, sidebar callout copy and colour, metal messages, and the initial number of visible cards. An image-banner block shows different artwork for Step 1 and Step 2, with a separate desktop aspect ratio for each step (Disable / 5:2 / 16:9).


9. UX details

  • Sticky sidebar on desktop, full-screen drawer on mobile. On mobile the bundle summary moves into a full-screen overlay (_syncMobileAsidePortal), positioned below the header with a measured offset.
  • 3-step progress bar (Chain → Charms → Added). Step 1 is clickable and resets the builder, which also clears the metal filter.
  • "Show more" that stays open. The host remembers which grids were expanded (_showMoreExpanded), so state updates don't collapse them again.
  • Hover image swap that matches the site's collection cards (second media item fades in from 750px wide, disabled under prefers-reduced-motion). If Liquid didn't supply a second image, upgradeGridCardHoverImages fetches /products/{handle}.js to get one.
  • Drag-to-scroll tab strip for long tab lists on desktop.
  • Accessibility: aria-busy on async buttons and cart lines, labelled remove buttons, unavailable cards with a hidden select and a text explanation, and reduced-motion support.

Lessons learned

  1. On Shopify's CDN, use import maps, not relative imports, for multi-file ES modules. Map bare specifiers to asset_url so every file keeps its version string.
  2. One custom element, many stateless functions. A single host owning state was much easier to debug than several web components trying to stay in sync.
  3. Don't re-render images you don't need to. Update existing nodes after first paint. Safari makes the cost of skipping this very visible.
  4. Model bundles with a per-add group ID in a hidden property. Never use a display label as a join key.
  5. When changing several cart lines in sequence, re-read the cart before each change. Line keys aren't stable across changes.
  6. To change a third-party library's click behaviour, use a capture-phase listener and decide synchronously. It's less invasive than forking the library and survives library updates.
  7. Keep business rules where the merchant already manages the data. Reading the metal from variant titles meant no new metafields and no new admin workflow.

What's next

  • Move the bundle discount into a Shopify Discount Function that reads _Bundle Group and Location from line properties, so the builder's price and the checkout price come from the same source.
  • Evaluate Cart Transform to merge the lines into a single bundle line at checkout for cleaner order presentation.
  • Data-driven metal tokens (a theme setting or metaobject) if the range grows beyond gold and silver.

**Stack: Liquid, vanilla JS web components, ES module import maps, the Shopify Ajax Cart API and Liquid Ajax Cart.

Top comments (0)