repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

250 lines · 16.7 KB · download this file

// Store add-on: marks sold-out items, keeps the cart, and sends checkout
// through Stripe. The cart lives in this browser only (localStorage, no
// cookies). Without JavaScript each item's form still works on its own (the
// server answers with a page that continues to Stripe).
(() => {
  const KEY = 'bf-store-cart';
  const forms = [...document.querySelectorAll('form.store-buy')];
  const load = () => { try { const c = JSON.parse(localStorage.getItem(KEY) || '{}'); return c && Array.isArray(c.items) ? c : {items: []}; } catch { return {items: []}; } };
  const save = cart => { try { localStorage.setItem(KEY, JSON.stringify(cart)); } catch {} };
  let cart = load();
  // Paid: the cart is done with.
  if (location.pathname === '/x/store/thanks') { cart = {items: []}; save(cart); }
  const money = (amount, c = cart) => {
    const value = amount / (Number(c.minor) || 100);
    try { return new Intl.NumberFormat(document.documentElement.lang || undefined, {style: 'currency', currency: (c.currency || 'usd').toUpperCase()}).format(value); }
    catch { return value.toFixed(Number(c.minor) === 1 ? 0 : 2); }
  };
  let left = {};
  async function checkout(body, status, button) {
    button.disabled = true; status.textContent = 'Opening secure checkout…';
    try {
      const response = await fetch('/x/store/checkout', {method: 'POST', body, headers: {'X-Requested-With': 'fetch'}});
      const result = await response.json();
      if (!result.ok || !result.url) throw new Error(result.message || 'Checkout is unavailable right now.');
      window.location.assign(result.url);
    } catch (error) {
      status.textContent = error.message || 'Checkout is unavailable right now.';
      button.disabled = false;
    }
  }

  // ---- The cart: a button in the corner, and a panel with the items -----------------
  let toggle = null, panel = null;
  function build() {
    if (toggle) return;
    toggle = document.createElement('button');
    toggle.type = 'button'; toggle.className = 'store-cart-toggle'; toggle.hidden = true;
    toggle.addEventListener('click', () => open(true));
    panel = document.createElement('dialog');
    panel.className = 'store-cart'; panel.setAttribute('aria-label', 'Your cart');
    panel.addEventListener('click', event => { if (event.target === panel) panel.close(); });
    document.body.append(toggle, panel);
  }
  function count() { return cart.items.reduce((n, i) => n + i.qty, 0); }
  function render() {
    if (!cart.items.length && !forms.some(f => f.dataset.cart)) { if (toggle) toggle.hidden = true; return; }
    build();
    toggle.hidden = !cart.items.length;
    toggle.textContent = `Cart · ${count()}`;
    toggle.setAttribute('aria-label', `Your cart: ${count()} ${count() === 1 ? 'item' : 'items'}`);
    panel.replaceChildren();
    const head = document.createElement('div'); head.className = 'store-cart__head';
    const title = document.createElement('h2'); title.textContent = 'Your cart';
    const close = document.createElement('button'); close.type = 'button'; close.className = 'store-cart__close'; close.textContent = '×'; close.setAttribute('aria-label', 'Close the cart');
    close.addEventListener('click', () => panel.close());
    head.append(title, close); panel.append(head);
    if (!cart.items.length) { const p = document.createElement('p'); p.textContent = 'Your cart is empty.'; panel.append(p); return; }
    const list = document.createElement('ul'); list.className = 'store-cart__items';
    for (const item of cart.items) {
      const li = document.createElement('li'); li.className = 'store-cart__item';
      if (item.image) { const img = document.createElement('img'); img.src = item.image; img.alt = ''; img.loading = 'lazy'; li.append(img); }
      const name = document.createElement('span'); name.className = 'store-cart__name'; name.textContent = item.title;
      const qty = document.createElement('select'); qty.setAttribute('aria-label', `How many ${item.title}`);
      const pid = item.id.split('.')[0];
      const most = Math.min(10, pid in left ? Math.max(left[pid], item.qty) : 10);
      for (let n = 1; n <= most; n++) { const o = new Option(String(n), String(n), false, n === item.qty); qty.append(o); }
      qty.addEventListener('change', () => { item.qty = Number(qty.value); save(cart); render(); open(false); });
      const price = document.createElement('span'); price.className = 'store-cart__price'; price.textContent = money(item.price * item.qty);
      const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'store-cart__remove'; remove.textContent = 'remove';
      remove.setAttribute('aria-label', `Remove ${item.title}`);
      remove.addEventListener('click', () => { cart.items = cart.items.filter(i => i !== item); save(cart); render(); if (cart.items.length) open(false); else panel.close(); });
      li.append(name, qty, price, remove); list.append(li);
    }
    const total = document.createElement('p'); total.className = 'store-cart__total';
    total.textContent = `Subtotal ${money(cart.items.reduce((t, i) => t + i.price * i.qty, 0))}`;
    const note = document.createElement('p'); note.className = 'store-cart__note'; note.textContent = 'Shipping, if any, is added at checkout.';
    const pay = document.createElement('button'); pay.type = 'button'; pay.className = 'buttonlike store-cart__checkout'; pay.textContent = 'Check out';
    const status = document.createElement('p'); status.className = 'store-cart__status'; status.setAttribute('role', 'status');
    pay.addEventListener('click', () => {
      const body = new FormData();
      cart.items.forEach(i => body.append('item', `${i.id}:${i.qty}`));
      body.append('back', location.pathname.startsWith('/x/') ? '/' : location.pathname);
      checkout(body, status, pay);
    });
    panel.append(list, total, note, pay, status);
  }
  function open(focus) { if (!panel) return; if (!panel.open) panel.showModal(); if (focus) panel.querySelector('.store-cart__checkout, .store-cart__close')?.focus(); }
  // The option a form has chosen: a hidden field the product page keeps up to
  // date, a checked button, or the only one (each with its label and price).
  function chosen(form) {
    return form.querySelector('input[type=hidden][name=option]') || form.querySelector('input[name=option]:checked') || form.querySelector('select[name=option]')?.selectedOptions[0] || null;
  }
  function add(form) {
    const pid = form.querySelector('[name=product]').value;
    const n = Math.max(1, Math.min(10, Math.round(Number(form.querySelector('[name=quantity]')?.value) || 1)));
    const d = form.dataset;
    // An option (a size, a colour): its own line in the cart, at its own price.
    const opt = chosen(form), value = opt ? (opt.value || '') : '';
    const id = value ? `${pid}.${value}` : pid;
    const title = opt && opt.dataset.label && form.dataset.options ? `${d.title} (${opt.dataset.label})` : d.title;
    const price = opt && opt.dataset.price ? Number(opt.dataset.price) : Number(d.price);
    // A shop that changed its currency starts the cart again.
    if (cart.items.length && cart.currency !== d.currency) cart = {items: []};
    cart.currency = d.currency; cart.minor = Number(d.minor) || 100;
    const have = cart.items.find(i => i.id === id);
    const most = Math.min(10, pid in left ? left[pid] : 10);
    if (have) have.qty = Math.min(most, have.qty + n);
    else cart.items.push({id, title, price, image: d.image || '', qty: Math.min(most, n)});
    save(cart); render();
  }
  // ---- A product's own page: its pictures, colours, sizes and quantity -----------------
  const page = document.querySelector('.store-buy--page');
  if (page) {
    const opts = (() => { try { return JSON.parse(page.dataset.options || '[]'); } catch { return []; } })();
    const hidden = page.querySelector('input[type=hidden][name=option]');
    const price = document.querySelector('[data-store-price]'), button = page.querySelector('.store-buy__button');
    const buyWords = () => page.dataset.cart || button.dataset.words || button.textContent;
    button.dataset.words = buyWords();
    const gallery = document.querySelector('[data-store-gallery]');
    const main = gallery?.querySelector('[data-store-main]');
    const count = gallery?.querySelector('[data-store-count]');
    const thumbs = gallery ? [...gallery.querySelectorAll('.store-gallery__thumb')] : [];
    // The gallery: a thumbnail (hovered or clicked) shows its picture; the
    // arrows, and the arrow keys, step through those shown; "3 / 8" says where.
    const visible = () => thumbs.filter(t => !t.closest('li').hidden);
    const current = () => thumbs.find(t => t.getAttribute('aria-pressed') === 'true');
    function show(thumb) {
      if (!thumb || !main) return;
      if (main.getAttribute('src') !== thumb.dataset.src) main.src = thumb.dataset.src;
      thumbs.forEach(t => t.setAttribute('aria-pressed', t === thumb ? 'true' : 'false'));
      if (thumb.dataset.src && page.dataset.image !== undefined) page.dataset.image = thumb.dataset.src;
      const list = visible();
      if (count) count.textContent = list.length > 1 ? `${list.indexOf(thumb) + 1} / ${list.length}` : '';
      // Keep it in sight in the thumbnails' own column (or row), without moving the page.
      const ul = thumb.closest('ul');
      if (ul) {
        const r = thumb.getBoundingClientRect(), u = ul.getBoundingClientRect();
        if (r.top < u.top) ul.scrollTop -= u.top - r.top; else if (r.bottom > u.bottom) ul.scrollTop += r.bottom - u.bottom;
        if (r.left < u.left) ul.scrollLeft -= u.left - r.left; else if (r.right > u.right) ul.scrollLeft += r.right - u.right;
      }
      if (box?.open) box.querySelector('img').src = thumb.dataset.src;
    }
    function step(by) {
      const list = visible(); if (!list.length) return;
      const at = list.indexOf(current());
      show(list[(at + by + list.length) % list.length]);
    }
    const hovers = window.matchMedia('(hover: hover)');
    thumbs.forEach(t => {
      t.addEventListener('click', () => show(t));
      t.addEventListener('mouseenter', () => { if (hovers.matches) show(t); });
    });
    gallery?.querySelectorAll('[data-store-step]').forEach(b => b.addEventListener('click', () => step(Number(b.dataset.storeStep))));
    gallery?.addEventListener('keydown', e => { if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') { step(-1); e.preventDefault(); } if (e.key === 'ArrowRight' || e.key === 'ArrowDown') { step(1); e.preventDefault(); } });
    // The main picture full size, in a window of its own, stepping through the same pictures.
    let box = null;
    gallery?.querySelector('[data-store-zoom]')?.addEventListener('click', () => {
      if (!box) {
        box = document.createElement('dialog'); box.className = 'store-lightbox'; box.setAttribute('aria-label', 'Picture, full size');
        const img = document.createElement('img'); img.alt = main.alt;
        const close = document.createElement('button'); close.type = 'button'; close.className = 'store-lightbox__close'; close.textContent = '×'; close.setAttribute('aria-label', 'Close');
        close.addEventListener('click', () => box.close());
        box.append(img, close);
        if (thumbs.length > 1) {
          for (const [by, words, mark] of [[-1, 'Previous picture', '‹'], [1, 'Next picture', '›']]) {
            const b = document.createElement('button'); b.type = 'button'; b.className = `store-lightbox__nav store-lightbox__nav--${by < 0 ? 'prev' : 'next'}`;
            b.textContent = mark; b.setAttribute('aria-label', words); b.addEventListener('click', () => step(by)); box.append(b);
          }
        }
        box.addEventListener('click', e => { if (e.target === box) box.close(); });
        box.addEventListener('keydown', e => { if (e.key === 'ArrowLeft') step(-1); if (e.key === 'ArrowRight') step(1); });
        document.body.append(box);
      }
      box.querySelector('img').src = main.getAttribute('src');
      box.showModal();
    });
    // Colour swatches take their colour (a style set from here, as the page allows no inline styles).
    page.querySelectorAll('.store-swatch__chip[data-hex]').forEach(c => { c.style.backgroundColor = c.dataset.hex; c.classList.add('has-colour'); });
    // Choosing: the option that colour and size make, its price, the sizes that colour comes in, its pictures.
    function pickedValue(name) { return page.querySelector(`input[name=${name}]:checked`)?.value ?? page.querySelector(`input[type=hidden][name=${name}]`)?.value ?? ''; }
    function update(changed) {
      if (!opts.length) return;
      let colour = pickedValue('color'), size = pickedValue('size');
      const sizes = [...page.querySelectorAll('input[name=size][type=radio]')];
      if (sizes.length) {
        // Only the sizes made, and in stock, in this colour.
        sizes.forEach(r => { r.disabled = !opts.some(o => (!o.color || o.color === colour) && o.size === r.value && o.available !== false); });
        const current = sizes.find(r => r.checked);
        if (!current || current.disabled) { const first = sizes.find(r => !r.disabled); if (first) { first.checked = true; size = first.value; } }
      }
      let opt;
      if (hidden) {
        opt = opts.find(o => (!o.color || o.color === colour) && (!o.size || o.size === size)) || null;
        if (opt) { hidden.value = opt.id; hidden.dataset.label = opt.label; hidden.dataset.price = opt.price; }
      } else {
        const r = page.querySelector('input[name=option]:checked'); opt = r ? opts.find(o => o.id === r.value) : null;
      }
      page.querySelectorAll('[data-store-chosen]').forEach(s => { s.textContent = s.dataset.storeChosen === 'color' ? colour : size; });
      if (opt && price) price.textContent = money(opt.price, {currency: page.dataset.currency, minor: page.dataset.minor});
      const can = opt && opt.available !== false;
      button.disabled = !can; button.textContent = can ? buyWords() : 'Out of stock';
      if (thumbs.length) {
        // A colour chosen: its pictures (and those of no colour) are the ones shown.
        if (changed === 'color' || changed === 'start') {
          const mine = thumbs.filter(t => colour && t.dataset.color === colour);
          thumbs.forEach(t => { t.closest('li').hidden = mine.length > 0 && t.dataset.color !== '' && t.dataset.color !== colour; });
        }
        // Then the chosen size's (or option's) own picture, when it has one; else the colour's first.
        const own = opt && visible().find(t => (t.dataset.variants || '').split(' ').includes(String(opt.id)));
        if (own) show(own);
        else if (changed === 'color' || changed === 'start') show(visible().includes(current()) ? current() : visible()[0]);
      }
    }
    page.addEventListener('change', e => { if (['color', 'size', 'option'].includes(e.target.name)) update(e.target.name); });
    // The stepper: one fewer, one more (1 to 10, or as many as are left).
    const qty = page.querySelector('input[name=quantity]');
    page.querySelectorAll('[data-store-qty]').forEach(b => b.addEventListener('click', () => {
      const most = Number(qty.max) || 10;
      qty.value = Math.max(1, Math.min(most, (Number(qty.value) || 1) + Number(b.dataset.storeQty)));
    }));
    qty?.addEventListener('change', () => { qty.value = Math.max(1, Math.min(Number(qty.max) || 10, Math.round(Number(qty.value) || 1))); });
    update('start');
    if (!opts.length && thumbs.length) show(current() || thumbs[0]);
  }

  forms.forEach(form => form.addEventListener('submit', event => {
    event.preventDefault();
    const button = form.querySelector('.store-buy__button'), status = form.querySelector('.store-buy__status');
    if (!form.dataset.cart) { checkout(new FormData(form), status, button); return; }
    add(form);
    status.textContent = 'Added to your cart.';
    const label = button.textContent; button.textContent = 'Added ✓';
    setTimeout(() => { button.textContent = label; }, 1400);
    open(false);
  }));
  forms.filter(f => f.dataset.cart).forEach(form => { const b = form.querySelector('.store-buy__button'); if (!b.disabled) b.textContent = form.dataset.cart; });
  render();
  if (!forms.length && !cart.items.length) return;
  fetch('/x/store/stock.json', {cache: 'no-store'}).then(r => r.ok ? r.json() : {}).then(stock => {
    left = stock || {};
    forms.forEach(form => {
      const id = form.querySelector('[name=product]').value;
      if (!(id in left)) return;
      const n = left[id], item = form.closest('.store-item, .store-product'), qty = form.querySelector('[name=quantity]'), button = form.querySelector('.store-buy__button');
      if (n <= 0) { item?.classList.add('is-sold-out'); button.disabled = true; button.textContent = 'Sold out'; form.querySelectorAll('input, select, .store-stepper__step').forEach(el => { if (el.type !== 'hidden') el.disabled = true; }); return; }
      if (qty && qty.type === 'number') qty.max = Math.min(10, n);
    });
    render();
  }).catch(() => {});
})();