442 lines
15 KiB
JavaScript
442 lines
15 KiB
JavaScript
import { SHOP, CATEGORIES, DISHES, PROMOTIONS } from './menu.js'
|
||
import {
|
||
loadSettings, saveSettings, checkRepo, commitFiles, toCompressedDataUrl, dataUrlSize, GhError,
|
||
} from './gh.js'
|
||
|
||
const $ = (id) => document.getElementById(id)
|
||
const esc = (text) => String(text ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]))
|
||
const DRAFT_KEY = 'dine.menu.draft.v1'
|
||
const PREVIEW_KEY = 'dine.menu.v1'
|
||
|
||
const yuan = (cents) => (cents / 100).toFixed(cents % 100 === 0 ? 0 : 2)
|
||
const yuanOf = (text) => Math.round((Number(text) || 0) * 100)
|
||
|
||
let state = {
|
||
shop: { ...SHOP },
|
||
categories: structuredClone(CATEGORIES),
|
||
promotions: structuredClone(PROMOTIONS),
|
||
dishes: structuredClone(DISHES),
|
||
}
|
||
let dirty = false
|
||
let editingId = null
|
||
let editingImg = ''
|
||
let activeCat = 'all'
|
||
let cfg = loadSettings()
|
||
|
||
// ---------- 通用 ----------
|
||
|
||
let toastTimer = 0
|
||
function toast(text, tone = '') {
|
||
const el = $('toast')
|
||
el.textContent = text
|
||
el.className = `toast ${tone}`
|
||
el.hidden = false
|
||
clearTimeout(toastTimer)
|
||
toastTimer = setTimeout(() => { el.hidden = true }, 2600)
|
||
}
|
||
|
||
function markDirty(value = true) {
|
||
dirty = value
|
||
$('dirtyTip').hidden = !dirty
|
||
if (dirty) localStorage.setItem(DRAFT_KEY, JSON.stringify(state))
|
||
}
|
||
|
||
function catName(id) {
|
||
return state.categories.find((cat) => cat.id === id)?.name ?? '未分类'
|
||
}
|
||
|
||
// ---------- 渲染 ----------
|
||
|
||
function paintShop() {
|
||
$('shopName').value = state.shop.name ?? ''
|
||
$('shopSlogan').value = state.shop.slogan ?? ''
|
||
$('shopNotice').value = state.shop.notice ?? ''
|
||
$('shopHours').value = state.shop.hours ?? ''
|
||
}
|
||
|
||
function paintPromos() {
|
||
$('promoList').innerHTML = state.promotions.length === 0
|
||
? '<p class="hint">还没有规则,顾客就是原价。</p>'
|
||
: state.promotions.map((promo, index) => `
|
||
<div class="promo-row" data-index="${index}">
|
||
<span>满</span><input type="number" min="0" step="1" value="${yuan(promo.threshold)}" data-promo="threshold" aria-label="满多少元">
|
||
<span>减</span><input type="number" min="0" step="1" value="${yuan(promo.off)}" data-promo="off" aria-label="减多少元">
|
||
<button class="icon-btn" data-del-promo="${index}" type="button" aria-label="删除这条">✕</button>
|
||
</div>`).join('')
|
||
}
|
||
|
||
function paintFilter() {
|
||
const total = state.dishes.length
|
||
$('dishCount').textContent = `${total} 道(在售 ${state.dishes.filter((dish) => !dish.off).length})`
|
||
$('catFilter').innerHTML = [{ id: 'all', name: '全部' }, ...state.categories].map((cat) => `
|
||
<button type="button" data-cat="${cat.id}" class="${activeCat === cat.id ? 'on' : ''}">
|
||
${cat.icon ? `${cat.icon} ` : ''}${esc(cat.name)} <span>${cat.id === 'all' ? total : state.dishes.filter((dish) => dish.cat === cat.id).length}</span>
|
||
</button>`).join('')
|
||
}
|
||
|
||
function paintDishes() {
|
||
const list = state.dishes.filter((dish) => activeCat === 'all' || dish.cat === activeCat)
|
||
$('dishList').innerHTML = list.length === 0
|
||
? '<p class="hint">这个分类还没有菜,点右上角「新增菜品」。</p>'
|
||
: list.map((dish) => `
|
||
<div class="dish-row${dish.off ? ' off' : ''}" data-id="${dish.id}">
|
||
<div class="dish-thumb">${dish.img ? `<img src="${esc(dish.img)}" alt="">` : (dish.emoji ?? '🍽️')}</div>
|
||
<div class="dish-info">
|
||
<b>${esc(dish.name)}</b>
|
||
<small>${esc(catName(dish.cat))} · ${dish.hot ? '热门 · ' : ''}${dish.specs?.length ? `${dish.specs.length} 组规格 ` : ''}${dish.img ? '有图' : '用表情'}</small>
|
||
</div>
|
||
<div class="dish-right">
|
||
<span class="price">¥${yuan(dish.price)}</span>
|
||
<label class="switch" title="${dish.off ? '已下架' : '在售'}">
|
||
<input type="checkbox" data-toggle="${dish.id}" ${dish.off ? '' : 'checked'} aria-label="在售开关">
|
||
<span></span>
|
||
</label>
|
||
<button class="icon-btn" data-edit="${dish.id}" type="button" aria-label="编辑">✎</button>
|
||
</div>
|
||
</div>`).join('')
|
||
}
|
||
|
||
function paintAll() {
|
||
paintFilter()
|
||
paintDishes()
|
||
paintPromos()
|
||
}
|
||
|
||
// ---------- 店铺信息 ----------
|
||
|
||
for (const [id, key] of [['shopName', 'name'], ['shopSlogan', 'slogan'], ['shopNotice', 'notice'], ['shopHours', 'hours']]) {
|
||
$(id).addEventListener('input', (event) => {
|
||
state.shop[key] = event.target.value
|
||
markDirty()
|
||
})
|
||
}
|
||
|
||
// ---------- 满减 ----------
|
||
|
||
$('addPromo').addEventListener('click', () => {
|
||
state.promotions.push({ threshold: 10000, off: 1000, label: '满 100 减 10' })
|
||
paintPromos()
|
||
markDirty()
|
||
})
|
||
|
||
$('promoList').addEventListener('input', (event) => {
|
||
const field = event.target.dataset.promo
|
||
if (!field) return
|
||
const index = Number(event.target.closest('[data-index]').dataset.index)
|
||
const promo = state.promotions[index]
|
||
if (!promo) return
|
||
promo[field] = yuanOf(event.target.value)
|
||
promo.label = `满 ${yuan(promo.threshold)} 减 ${yuan(promo.off)}`
|
||
markDirty()
|
||
})
|
||
|
||
$('promoList').addEventListener('click', (event) => {
|
||
const button = event.target.closest('[data-del-promo]')
|
||
if (!button) return
|
||
state.promotions.splice(Number(button.dataset.delPromo), 1)
|
||
paintPromos()
|
||
markDirty()
|
||
})
|
||
|
||
// ---------- 菜品列表 ----------
|
||
|
||
$('catFilter').addEventListener('click', (event) => {
|
||
const button = event.target.closest('[data-cat]')
|
||
if (!button) return
|
||
activeCat = button.dataset.cat
|
||
paintFilter()
|
||
paintDishes()
|
||
})
|
||
|
||
$('dishList').addEventListener('change', (event) => {
|
||
const id = event.target.dataset.toggle
|
||
if (!id) return
|
||
const dish = state.dishes.find((item) => item.id === id)
|
||
if (!dish) return
|
||
dish.off = !event.target.checked
|
||
paintDishes()
|
||
markDirty()
|
||
})
|
||
|
||
$('dishList').addEventListener('click', (event) => {
|
||
const button = event.target.closest('[data-edit]')
|
||
if (!button) return
|
||
openEditor(button.dataset.edit)
|
||
})
|
||
|
||
// ---------- 编辑弹层 ----------
|
||
|
||
function specsToText(specs) {
|
||
return (specs ?? []).map((group) => `${group.name}: ${group.options.join(',')}`).join('\n')
|
||
}
|
||
|
||
function textToSpecs(text) {
|
||
return String(text ?? '').split('\n').map((line) => line.trim()).filter(Boolean).map((line) => {
|
||
const index = line.search(/[::]/)
|
||
if (index < 0) return null
|
||
const name = line.slice(0, index).trim()
|
||
const options = line.slice(index + 1).split(/[,,、]/).map((item) => item.trim()).filter(Boolean)
|
||
return name && options.length ? { name, options } : null
|
||
}).filter(Boolean)
|
||
}
|
||
|
||
function extrasToText(extras) {
|
||
return (extras ?? []).map((extra) => `${extra.name}: ${yuan(extra.price)}`).join('\n')
|
||
}
|
||
|
||
function textToExtras(text) {
|
||
return String(text ?? '').split('\n').map((line) => line.trim()).filter(Boolean).map((line) => {
|
||
const match = line.match(/^(.+?)\s*[::]\s*([\d.]+)\s*元?$/) ?? line.match(/^(.+?)\s+([\d.]+)\s*元?$/)
|
||
if (!match) return null
|
||
return { name: match[1].trim(), price: yuanOf(match[2]) }
|
||
}).filter(Boolean)
|
||
}
|
||
|
||
function paintEditorArt() {
|
||
$('picPreview').innerHTML = editingImg
|
||
? `<img src="${esc(editingImg)}" alt="">`
|
||
: '🍽️'
|
||
}
|
||
|
||
function openEditor(id) {
|
||
editingId = id
|
||
const dish = id === 'new' ? null : state.dishes.find((item) => item.id === id)
|
||
editingImg = dish?.img ?? ''
|
||
|
||
$('editTitle').textContent = dish ? '编辑菜品' : '新增菜品'
|
||
$('deleteDish').hidden = !dish
|
||
$('fName').value = dish?.name ?? ''
|
||
$('fPrice').value = dish ? yuan(dish.price) : ''
|
||
$('fDesc').value = dish?.desc ?? ''
|
||
$('fTags').value = (dish?.tags ?? []).join(', ')
|
||
$('fHot').checked = Boolean(dish?.hot)
|
||
$('fSpecs').value = specsToText(dish?.specs)
|
||
$('fExtras').value = extrasToText(dish?.extras)
|
||
$('fCat').innerHTML = state.categories.map((cat) =>
|
||
`<option value="${cat.id}"${dish?.cat === cat.id ? ' selected' : ''}>${esc(cat.name)}</option>`).join('')
|
||
paintEditorArt()
|
||
$('editSheet').hidden = false
|
||
}
|
||
|
||
function closeEditor() {
|
||
$('editSheet').hidden = true
|
||
editingId = null
|
||
editingImg = ''
|
||
}
|
||
|
||
document.addEventListener('click', (event) => {
|
||
if (event.target.closest('[data-close="editSheet"]')) closeEditor()
|
||
const close = event.target.closest('[data-close]')
|
||
if (close) closeEditor()
|
||
})
|
||
|
||
$('addDish').addEventListener('click', () => openEditor('new'))
|
||
|
||
$('picInput').addEventListener('change', async (event) => {
|
||
const file = event.target.files?.[0]
|
||
if (!file) return
|
||
try {
|
||
toast('正在压缩图片…')
|
||
editingImg = await toCompressedDataUrl(file)
|
||
paintEditorArt()
|
||
toast(`图片好了,约 ${Math.round(dataUrlSize(editingImg) / 1024)} KB`, 'ok')
|
||
} catch (error) {
|
||
toast(error.message || '图片处理失败', 'bad')
|
||
}
|
||
event.target.value = ''
|
||
})
|
||
|
||
$('picClear').addEventListener('click', () => {
|
||
editingImg = ''
|
||
paintEditorArt()
|
||
})
|
||
|
||
$('saveDish').addEventListener('click', () => {
|
||
const name = $('fName').value.trim()
|
||
const price = yuanOf($('fPrice').value)
|
||
if (!name) return toast('菜名不能空着', 'bad')
|
||
if (price <= 0) return toast('价格要大于 0', 'bad')
|
||
|
||
const patch = {
|
||
name,
|
||
cat: $('fCat').value,
|
||
price,
|
||
desc: $('fDesc').value.trim(),
|
||
tags: $('fTags').value.split(/[,,]/).map((tag) => tag.trim()).filter(Boolean),
|
||
hot: $('fHot').checked,
|
||
specs: textToSpecs($('fSpecs').value),
|
||
extras: textToExtras($('fExtras').value),
|
||
}
|
||
|
||
if (editingId === 'new') {
|
||
const id = `d${Date.now().toString(36)}`
|
||
state.dishes.unshift({
|
||
id, emoji: '🍽️', ...patch, ...(editingImg ? { img: editingImg } : {}),
|
||
})
|
||
} else {
|
||
const dish = state.dishes.find((item) => item.id === editingId)
|
||
if (!dish) return closeEditor()
|
||
Object.assign(dish, patch)
|
||
if (editingImg) dish.img = editingImg
|
||
else delete dish.img
|
||
}
|
||
closeEditor()
|
||
paintAll()
|
||
markDirty()
|
||
toast('已保存,别忘了发布', 'ok')
|
||
})
|
||
|
||
$('deleteDish').addEventListener('click', () => {
|
||
const dish = state.dishes.find((item) => item.id === editingId)
|
||
if (!dish) return closeEditor()
|
||
if (!confirm(`确定删除「${dish.name}」?`)) return
|
||
state.dishes = state.dishes.filter((item) => item.id !== dish.id)
|
||
closeEditor()
|
||
paintAll()
|
||
markDirty()
|
||
toast('已删除,别忘了发布', 'ok')
|
||
})
|
||
|
||
// ---------- 仓库连接 ----------
|
||
|
||
function fillSettings() {
|
||
$('repoInput').value = `${cfg.owner}/${cfg.repo}`
|
||
$('branchInput').value = cfg.branch
|
||
$('tokenInput').value = cfg.token ? '••••••••' : ''
|
||
$('connTip').textContent = cfg.token ? `仓库 ${cfg.owner}/${cfg.repo}` : '仓库未连接'
|
||
}
|
||
|
||
function readSettings() {
|
||
const repoText = $('repoInput').value.trim()
|
||
const slash = repoText.indexOf('/')
|
||
if (slash > 0) {
|
||
cfg.owner = repoText.slice(0, slash).trim()
|
||
cfg.repo = repoText.slice(slash + 1).trim()
|
||
}
|
||
cfg.branch = $('branchInput').value.trim() || 'main'
|
||
const token = $('tokenInput').value.trim()
|
||
if (token && !token.startsWith('•')) cfg.token = token
|
||
cfg = saveSettings(cfg)
|
||
fillSettings()
|
||
}
|
||
|
||
$('repoInput').addEventListener('change', readSettings)
|
||
$('branchInput').addEventListener('change', readSettings)
|
||
$('tokenInput').addEventListener('change', readSettings)
|
||
|
||
$('testBtn').addEventListener('click', async () => {
|
||
readSettings()
|
||
const stateEl = $('connState')
|
||
stateEl.className = 'state'
|
||
stateEl.textContent = '连接中…'
|
||
try {
|
||
const info = await checkRepo(cfg)
|
||
stateEl.className = 'state ok'
|
||
stateEl.textContent = `连上了:${info.login} · ${info.fullName}(${info.isPrivate ? '私有' : '公开'})`
|
||
if (info.branch !== cfg.branch) {
|
||
cfg.branch = info.branch
|
||
saveSettings(cfg)
|
||
$('branchInput').value = info.branch
|
||
}
|
||
} catch (error) {
|
||
stateEl.className = 'state bad'
|
||
stateEl.textContent = error.message
|
||
}
|
||
})
|
||
|
||
// ---------- 发布 ----------
|
||
|
||
function collectFiles() {
|
||
const payload = {
|
||
shop: state.shop,
|
||
categories: state.categories,
|
||
promotions: state.promotions,
|
||
dishes: state.dishes,
|
||
}
|
||
return [{ path: 'menu.json', content: `${JSON.stringify(payload, null, 2)}\n` }]
|
||
}
|
||
|
||
function publishMessage() {
|
||
const parts = [`${state.dishes.length} 道菜`]
|
||
const images = state.dishes.filter((dish) => dish.img).length
|
||
if (images) parts.push(`${images} 张图`)
|
||
if (state.promotions.length) parts.push(`${state.promotions.length} 条满减`)
|
||
return `后厨后台更新菜单:${parts.join(' · ')}(${new Date().toLocaleString('zh-CN', { hour12: false })})`
|
||
}
|
||
|
||
$('publish').addEventListener('click', async () => {
|
||
readSettings()
|
||
const button = $('publish')
|
||
if (!cfg.token) return toast('先填 GitHub 令牌并测试连接', 'bad')
|
||
if (state.dishes.length === 0) return toast('至少留一道菜', 'bad')
|
||
|
||
button.disabled = true
|
||
const original = button.textContent
|
||
button.textContent = '发布中…'
|
||
try {
|
||
const result = await commitFiles(cfg, collectFiles(), publishMessage(), (step) => {
|
||
$('connState').className = 'state'
|
||
$('connState').textContent = step
|
||
button.textContent = step
|
||
})
|
||
localStorage.setItem(PREVIEW_KEY, JSON.stringify({
|
||
shop: state.shop, categories: state.categories, promotions: state.promotions, dishes: state.dishes,
|
||
}))
|
||
localStorage.removeItem(DRAFT_KEY)
|
||
dirty = false
|
||
$('dirtyTip').hidden = true
|
||
toast('发布成功,仓库已更新', 'ok')
|
||
$('connState').className = 'state ok'
|
||
$('connState').innerHTML = `已提交 <a href="${result.url}" target="_blank" rel="noopener">${result.sha.slice(0, 7)}</a> · 本机预览已更新(其他设备读仓库里的 menu.json)`
|
||
} catch (error) {
|
||
const message = error instanceof GhError ? error.message : `发布失败:${error.message}`
|
||
toast(message, 'bad')
|
||
$('connState').className = 'state bad'
|
||
$('connState').textContent = message
|
||
} finally {
|
||
button.disabled = false
|
||
button.textContent = original
|
||
}
|
||
})
|
||
|
||
// ---------- 草稿 ----------
|
||
|
||
function loadDraft() {
|
||
const raw = localStorage.getItem(DRAFT_KEY)
|
||
if (!raw) return
|
||
try {
|
||
const draft = JSON.parse(raw)
|
||
if (draft.dishes) {
|
||
state = { shop: draft.shop ?? state.shop, categories: draft.categories ?? state.categories, promotions: draft.promotions ?? state.promotions, dishes: draft.dishes }
|
||
paintAll()
|
||
}
|
||
$('draftBanner').hidden = false
|
||
} catch {}
|
||
}
|
||
|
||
$('useDraft').addEventListener('click', () => {
|
||
$('draftBanner').hidden = true
|
||
markDirty(true)
|
||
paintAll()
|
||
toast('用的是本地草稿', 'ok')
|
||
})
|
||
|
||
$('dropDraft').addEventListener('click', () => {
|
||
localStorage.removeItem(DRAFT_KEY)
|
||
$('draftBanner').hidden = true
|
||
})
|
||
|
||
window.addEventListener('beforeunload', (event) => {
|
||
if (!dirty) return
|
||
event.preventDefault()
|
||
event.returnValue = ''
|
||
})
|
||
|
||
// ---------- 启动 ----------
|
||
|
||
paintShop()
|
||
paintAll()
|
||
fillSettings()
|
||
loadDraft()
|
||
console.log('[admin] 菜品', state.dishes.length, '分类', state.categories.length, '满减', state.promotions.length)
|