Files
smartmenu-collina/src/components/public/PublicMenu.tsx
T
Jorem Juárez 084a191061 Add per-restaurant macros toggle and public list view
Feature 1 — showMacros toggle:
- Restaurant.showMacros boolean (default false) so existing menus (e.g. NOCNEX)
  never publish with empty macros (migration 0004; default applies to existing rows)
- Editor toggle in the Palette tab, saved via the existing /settings endpoint
- Read live (not from the snapshot) in the public page and /menu API so it takes
  effect immediately without republishing; old snapshots default off
- When off, the public menu hides every macro layer: card flip + 'tap to see
  macros', the gallery macros, and the macro color-code legend

Feature 2 — public list view:
- Card/list toggle in the public menu; preference is NOT persisted (always starts
  on cards)
- New ListRow: compact traditional rows (name + price + allergen tags); tap the
  name to expand image + description (accordion); tap the image to reveal macros
  (only when showMacros is on)

i18n: viewCards/viewList (menu) and showMacros/showMacrosHint (editor) in es/en at parity.
Glassmorphism, mobile-first and safe areas preserved. Existing features untouched
(versioning, import, consultant, QR, i18n).

Verified: build passes; 4 migrations apply in order; existing rows default false;
toggling via /settings updates /menu live without republish.
2026-06-15 14:32:44 -06:00

406 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client';
import { useMemo, useRef, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import type { Locale } from '@/i18n/config';
import type { MenuSnapshot, SnapshotProduct } from '@/lib/types';
import { pickText } from '@/lib/text';
import LanguageSwitch from '@/components/LanguageSwitch';
import DishCard from './DishCard';
import ListRow from './ListRow';
import MacroLegend from './MacroLegend';
import Gallery from './Gallery';
import AiConsultant from './AiConsultant';
type ViewMode = 'cards' | 'list';
type CartLine = { product: SnapshotProduct; qty: number };
export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: string }) {
const locale = useLocale() as Locale;
const t = useTranslations('menu');
const sections = useMemo(
() =>
[...menu.sections]
.sort((a, b) => a.order - b.order)
.map((s) => ({
...s,
products: s.products.filter((p) => p.isActive),
})),
[menu.sections],
);
const [activeSection, setActiveSection] = useState(sections[0]?.id ?? '');
const [gallery, setGallery] = useState<SnapshotProduct | null>(null);
const [aiOpen, setAiOpen] = useState(false);
const [actionsOpen, setActionsOpen] = useState(false);
const [cart, setCart] = useState<CartLine[]>([]);
const [orderOpen, setOrderOpen] = useState(false);
const [waiterOpen, setWaiterOpen] = useState(false);
const [toast, setToast] = useState<string | null>(null);
// View preference is intentionally not persisted — always starts on cards.
const [view, setView] = useState<ViewMode>('cards');
const sectionRefs = useRef<Record<string, HTMLElement | null>>({});
const ordersEnabled = menu.restaurant.ordersEnabled;
const showMacros = menu.restaurant.showMacros;
function scrollToSection(id: string) {
setActiveSection(id);
sectionRefs.current[id]?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function addToCart(p: SnapshotProduct) {
setCart((prev) => {
const existing = prev.find((l) => l.product.id === p.id);
if (existing) return prev.map((l) => (l.product.id === p.id ? { ...l, qty: l.qty + 1 } : l));
return [...prev, { product: p, qty: 1 }];
});
showToast('+1');
}
function showToast(msg: string) {
setToast(msg);
setTimeout(() => setToast(null), 2200);
}
const cartCount = cart.reduce((n, l) => n + l.qty, 0);
return (
<div className="safe-pt-header mx-auto min-h-screen max-w-2xl px-4 pb-32">
{/* Header */}
<header className="mb-4 flex items-center justify-between gap-3">
<h1 className="display text-2xl font-semibold leading-tight">{menu.restaurant.name}</h1>
<LanguageSwitch />
</header>
{/* Section tabs */}
{sections.length > 0 && (
<nav className="safe-top-sticky sticky z-20 -mx-1 mb-4 flex gap-2 overflow-x-auto px-1 py-1 no-scrollbar">
{sections.map((s) => (
<button
key={s.id}
onClick={() => scrollToSection(s.id)}
className={`glass-pill shrink-0 rounded-full px-4 py-2 text-sm font-medium transition ${
activeSection === s.id ? 'ring-2 ring-[var(--accent)]/40' : ''
}`}
>
{pickText(s.name, locale)}
</button>
))}
</nav>
)}
{/* View toggle (cards vs traditional list). Not persisted. */}
<div className="mb-4 flex items-center justify-end gap-3">
{showMacros && <div className="min-w-0 flex-1"><MacroLegend /></div>}
<div className="glass-pill inline-flex shrink-0 rounded-full p-1 text-sm">
<button
onClick={() => setView('cards')}
className={`rounded-full px-3 py-1 font-medium transition ${
view === 'cards' ? 'bg-white/70 text-[var(--text)] shadow' : 'text-[var(--text)]/60'
}`}
>
{t('viewCards')}
</button>
<button
onClick={() => setView('list')}
className={`rounded-full px-3 py-1 font-medium transition ${
view === 'list' ? 'bg-white/70 text-[var(--text)] shadow' : 'text-[var(--text)]/60'
}`}
>
{t('viewList')}
</button>
</div>
</div>
{/* Sections */}
{sections.map((s) => (
<section
key={s.id}
ref={(el) => {
sectionRefs.current[s.id] = el;
}}
className="mb-8 scroll-mt-20"
>
<h2 className="display mb-3 text-xl font-semibold">{pickText(s.name, locale)}</h2>
{s.products.length === 0 ? (
<p className="text-sm text-[var(--text)]/50">{t('empty')}</p>
) : view === 'list' ? (
<div className="flex flex-col gap-2">
{s.products.map((p) => (
<ListRow
key={p.id}
product={p}
showMacros={showMacros}
ordersEnabled={ordersEnabled}
onAdd={ordersEnabled ? addToCart : undefined}
/>
))}
</div>
) : (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{s.products.map((p, i) => (
<DishCard
key={p.id}
product={p}
index={i}
onOpenGallery={setGallery}
onAdd={ordersEnabled ? addToCart : undefined}
ordersEnabled={ordersEnabled}
showMacros={showMacros}
/>
))}
</div>
)}
</section>
))}
{/* Floating actions */}
<div className="safe-bottom-fab fixed left-1/2 z-30 flex -translate-x-1/2 flex-col items-center gap-3">
{actionsOpen && (
<div className="animate-spawn flex flex-col items-stretch gap-2">
{ordersEnabled && (
<button
onClick={() => {
setOrderOpen(true);
setActionsOpen(false);
}}
className="glass rounded-full px-5 py-3 text-sm font-medium"
>
{t('placeOrder')} {cartCount > 0 && `(${cartCount})`}
</button>
)}
<button
onClick={() => {
setWaiterOpen(true);
setActionsOpen(false);
}}
className="glass rounded-full px-5 py-3 text-sm font-medium"
>
{t('callWaiter')}
</button>
<button
onClick={() => {
window.scrollTo({ top: 0, behavior: 'smooth' });
setActionsOpen(false);
}}
className="glass rounded-full px-5 py-3 text-sm font-medium"
>
{t('viewFull')}
</button>
</div>
)}
<div className="flex items-center gap-3">
<button
onClick={() => setAiOpen(true)}
className="glass rounded-full px-5 py-3 text-sm font-semibold shadow-lg"
>
✨ {t('askAi')}
</button>
<button
onClick={() => setActionsOpen((o) => !o)}
className="flex h-12 w-12 items-center justify-center rounded-full bg-[var(--accent)] text-2xl text-white shadow-lg transition"
aria-label={t('actions')}
>
<span className={`transition-transform ${actionsOpen ? 'rotate-45' : ''}`}>+</span>
</button>
</div>
</div>
{/* Modals */}
{gallery && (
<Gallery product={gallery} onClose={() => setGallery(null)} showMacros={showMacros} />
)}
{aiOpen && <AiConsultant slug={slug} onClose={() => setAiOpen(false)} />}
{orderOpen && (
<OrderPanel
slug={slug}
cart={cart}
setCart={setCart}
onClose={() => setOrderOpen(false)}
onSent={() => {
setCart([]);
setOrderOpen(false);
showToast(t('orderSent'));
}}
/>
)}
{waiterOpen && (
<WaiterPanel
slug={slug}
onClose={() => setWaiterOpen(false)}
onSent={() => {
setWaiterOpen(false);
showToast(t('waiterCalled'));
}}
/>
)}
{toast && (
<div className="animate-spawn fixed bottom-24 left-1/2 z-50 -translate-x-1/2 rounded-full bg-[var(--text)] px-5 py-2 text-sm text-white shadow-lg">
{toast}
</div>
)}
</div>
);
}
function TableInput({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const t = useTranslations('menu');
return (
<input
type="number"
min={1}
inputMode="numeric"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={t('tableNumber')}
className="glass-soft w-full rounded-2xl px-4 py-3 text-center text-lg outline-none"
/>
);
}
function OrderPanel({
slug,
cart,
setCart,
onClose,
onSent,
}: {
slug: string;
cart: CartLine[];
setCart: React.Dispatch<React.SetStateAction<CartLine[]>>;
onClose: () => void;
onSent: () => void;
}) {
const locale = useLocale() as Locale;
const t = useTranslations('menu');
const [table, setTable] = useState('');
const [sending, setSending] = useState(false);
function setQty(id: string, delta: number) {
setCart((prev) =>
prev
.map((l) => (l.product.id === id ? { ...l, qty: l.qty + delta } : l))
.filter((l) => l.qty > 0),
);
}
async function send() {
if (!table || cart.length === 0 || sending) return;
setSending(true);
try {
await fetch(`/api/${slug}/order`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
tableNumber: Number(table),
items: cart.map((l) => ({
productId: l.product.id,
name: pickText(l.product.name, locale),
qty: l.qty,
})),
}),
});
onSent();
} finally {
setSending(false);
}
}
return (
<Sheet title={t('yourOrder')} onClose={onClose}>
<div className="flex flex-col gap-2">
{cart.length === 0 && <p className="text-sm text-[var(--text)]/60">—</p>}
{cart.map((l) => (
<div key={l.product.id} className="glass-soft flex items-center gap-2 rounded-2xl px-3 py-2">
<span className="flex-1 text-sm">{pickText(l.product.name, locale)}</span>
<button onClick={() => setQty(l.product.id, -1)} className="px-2 text-lg">
−
</button>
<span className="w-5 text-center">{l.qty}</span>
<button onClick={() => setQty(l.product.id, 1)} className="px-2 text-lg">
+
</button>
</div>
))}
</div>
<TableInput value={table} onChange={setTable} />
<button
onClick={send}
disabled={!table || cart.length === 0 || sending}
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
>
{t('send')}
</button>
</Sheet>
);
}
function WaiterPanel({
slug,
onClose,
onSent,
}: {
slug: string;
onClose: () => void;
onSent: () => void;
}) {
const t = useTranslations('menu');
const [table, setTable] = useState('');
const [sending, setSending] = useState(false);
async function send() {
if (!table || sending) return;
setSending(true);
try {
await fetch(`/api/${slug}/call-waiter`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tableNumber: Number(table) }),
});
onSent();
} finally {
setSending(false);
}
}
return (
<Sheet title={t('callWaiter')} onClose={onClose}>
<TableInput value={table} onChange={setTable} />
<button
onClick={send}
disabled={!table || sending}
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
>
{t('send')}
</button>
</Sheet>
);
}
function Sheet({
title,
onClose,
children,
}: {
title: string;
onClose: () => void;
children: React.ReactNode;
}) {
return (
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-3 backdrop-blur-sm sm:items-center">
<div className="glass flex w-full max-w-md flex-col gap-3 rounded-3xl p-4">
<div className="flex items-center justify-between">
<h3 className="display text-lg font-semibold">{title}</h3>
<button onClick={onClose} className="glass-pill rounded-full px-3 py-1">
✕
</button>
</div>
{children}
</div>
</div>
);
}