feat(V0.2): 列表拖动修复 + 打卡项组内拖动排序
- 任务列表/看板拖动: 激活后用非 passive touchmove preventDefault 拦截浏览器滚动接管, 修复列表长按抬起后 pointercancel 导致无法真正拖动 - 打卡: 列表按周期分组展示(每天/每周/每月/每年), 长按拖动组内排序(上下落点指示), 新增 POST /checkin/habits/reorder 重写 sortOrder; 新建项排到末尾 - 打卡卡片加 touch-action/user-select 防长按误触; 拖动结束 350ms 内抑制点击余波
This commit is contained in:
+42
-41
@@ -1,41 +1,42 @@
|
||||
import { api } from './client.js'
|
||||
|
||||
const q = (params) => {
|
||||
const s = new URLSearchParams()
|
||||
Object.entries(params || {}).forEach(([k, v]) => {
|
||||
if (v !== undefined && v !== null && v !== '') s.set(k, v)
|
||||
})
|
||||
const str = s.toString()
|
||||
return str ? '?' + str : ''
|
||||
}
|
||||
|
||||
// 打卡 / 日历
|
||||
export const checkinApi = {
|
||||
habits: (date) => api('/checkin/habits' + q({ date })),
|
||||
day: (date) => api('/checkin/day' + q({ date })),
|
||||
calendar: (month) => api('/checkin/calendar' + q({ month })),
|
||||
createHabit: (body) => api('/checkin/habits', { method: 'POST', body }),
|
||||
updateHabit: (id, body) => api(`/checkin/habits/${id}`, { method: 'PUT', body }),
|
||||
deleteHabit: (id, hard) => api(`/checkin/habits/${id}${hard ? '?hard=1' : ''}`, { method: 'DELETE' }),
|
||||
check: (id, date, note) => api(`/checkin/habits/${id}/check`, { method: 'POST', body: { date, note } }),
|
||||
uncheck: (id, date) => api(`/checkin/habits/${id}/check` + q({ date }), { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
// 检查清单
|
||||
export const checklistApi = {
|
||||
lists: (archived) => api('/checklists' + q({ archived: archived ? 1 : 0 })),
|
||||
list: (id) => api(`/checklists/${id}`),
|
||||
create: (body) => api('/checklists', { method: 'POST', body }),
|
||||
update: (id, body) => api(`/checklists/${id}`, { method: 'PUT', body }),
|
||||
remove: (id) => api(`/checklists/${id}`, { method: 'DELETE' }),
|
||||
duplicate: (id) => api(`/checklists/${id}/duplicate`, { method: 'POST', body: {} }),
|
||||
addItem: (id, body) => api(`/checklists/${id}/items`, { method: 'POST', body }),
|
||||
updateItem: (itemId, body) => api(`/checklists/items/${itemId}`, { method: 'PUT', body }),
|
||||
removeItem: (itemId) => api(`/checklists/items/${itemId}`, { method: 'DELETE' }),
|
||||
checkAll: (id, done) => api(`/checklists/${id}/check-all`, { method: 'POST', body: { done } }),
|
||||
templates: () => api('/checklists/templates'),
|
||||
template: (id) => api(`/checklists/templates/${id}`),
|
||||
createTemplate: (body) => api('/checklists/templates', { method: 'POST', body }),
|
||||
updateTemplate: (id, body) => api(`/checklists/templates/${id}`, { method: 'PUT', body }),
|
||||
removeTemplate: (id) => api(`/checklists/templates/${id}`, { method: 'DELETE' }),
|
||||
}
|
||||
import { api } from './client.js'
|
||||
|
||||
const q = (params) => {
|
||||
const s = new URLSearchParams()
|
||||
Object.entries(params || {}).forEach(([k, v]) => {
|
||||
if (v !== undefined && v !== null && v !== '') s.set(k, v)
|
||||
})
|
||||
const str = s.toString()
|
||||
return str ? '?' + str : ''
|
||||
}
|
||||
|
||||
// 打卡 / 日历
|
||||
export const checkinApi = {
|
||||
habits: (date) => api('/checkin/habits' + q({ date })),
|
||||
day: (date) => api('/checkin/day' + q({ date })),
|
||||
calendar: (month) => api('/checkin/calendar' + q({ month })),
|
||||
createHabit: (body) => api('/checkin/habits', { method: 'POST', body }),
|
||||
updateHabit: (id, body) => api(`/checkin/habits/${id}`, { method: 'PUT', body }),
|
||||
reorderHabits: (ids) => api('/checkin/habits/reorder', { method: 'POST', body: { ids } }),
|
||||
deleteHabit: (id, hard) => api(`/checkin/habits/${id}${hard ? '?hard=1' : ''}`, { method: 'DELETE' }),
|
||||
check: (id, date, note) => api(`/checkin/habits/${id}/check`, { method: 'POST', body: { date, note } }),
|
||||
uncheck: (id, date) => api(`/checkin/habits/${id}/check` + q({ date }), { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
// 检查清单
|
||||
export const checklistApi = {
|
||||
lists: (archived) => api('/checklists' + q({ archived: archived ? 1 : 0 })),
|
||||
list: (id) => api(`/checklists/${id}`),
|
||||
create: (body) => api('/checklists', { method: 'POST', body }),
|
||||
update: (id, body) => api(`/checklists/${id}`, { method: 'PUT', body }),
|
||||
remove: (id) => api(`/checklists/${id}`, { method: 'DELETE' }),
|
||||
duplicate: (id) => api(`/checklists/${id}/duplicate`, { method: 'POST', body: {} }),
|
||||
addItem: (id, body) => api(`/checklists/${id}/items`, { method: 'POST', body }),
|
||||
updateItem: (itemId, body) => api(`/checklists/items/${itemId}`, { method: 'PUT', body }),
|
||||
removeItem: (itemId) => api(`/checklists/items/${itemId}`, { method: 'DELETE' }),
|
||||
checkAll: (id, done) => api(`/checklists/${id}/check-all`, { method: 'POST', body: { done } }),
|
||||
templates: () => api('/checklists/templates'),
|
||||
template: (id) => api(`/checklists/templates/${id}`),
|
||||
createTemplate: (body) => api('/checklists/templates', { method: 'POST', body }),
|
||||
updateTemplate: (id, body) => api(`/checklists/templates/${id}`, { method: 'PUT', body }),
|
||||
removeTemplate: (id) => api(`/checklists/templates/${id}`, { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
// 打卡项组内拖动排序
|
||||
// 手势与任务列表/看板一致: 长按 400ms 原位抬起(震动), 之后拖动;
|
||||
// elementFromPoint 命中同一周期组内的 [data-habit-row] 作为落点,
|
||||
// 按指针在目标卡上半/下半决定插到其前/后, 松手提交。
|
||||
// 只允许组内 (每天/每周/每月/每年) 排序, 命中其他组视为无效落点。
|
||||
// 激活后用非 passive touchmove preventDefault 拦截浏览器滚动接管,
|
||||
// 保证纵向拖动期间指针事件持续派发 (同 useRowDrag 的教训)。
|
||||
export default function useHabitDrag({ onDrop }) {
|
||||
const [dragItem, setDragItem] = useState(null) // 拖动中的打卡项 (视觉态)
|
||||
const [over, setOver] = useState(null) // { id, after } 落点
|
||||
const st = useRef({ timer: null, active: false, startX: 0, startY: 0, item: null, over: null })
|
||||
const lastEnd = useRef(0)
|
||||
|
||||
const cleanup = useCallback(() => {
|
||||
if (st.current.timer) { clearTimeout(st.current.timer); st.current.timer = null }
|
||||
st.current.active = false
|
||||
st.current.over = null
|
||||
setDragItem(null)
|
||||
setOver(null)
|
||||
}, [])
|
||||
|
||||
useEffect(() => () => cleanup(), [cleanup])
|
||||
|
||||
/** 拖动刚结束 (350ms 内): 抑制松手合成的 click 误触打卡 */
|
||||
const justEnded = useCallback(() => Date.now() - lastEnd.current < 350, [])
|
||||
|
||||
const hitRow = (x, y) => {
|
||||
const el = document.elementFromPoint(x, y)
|
||||
const rowEl = el?.closest?.('[data-habit-row]')
|
||||
if (!rowEl) return null
|
||||
const r = rowEl.getBoundingClientRect()
|
||||
return { id: Number(rowEl.dataset.habitId), after: y > r.top + r.height / 2 }
|
||||
}
|
||||
|
||||
const onMove = (ev) => {
|
||||
const s = st.current
|
||||
if (!s.active) {
|
||||
if (s.timer && (Math.abs(ev.clientX - s.startX) > 10 || Math.abs(ev.clientY - s.startY) > 10)) {
|
||||
clearTimeout(s.timer); s.timer = null
|
||||
}
|
||||
return
|
||||
}
|
||||
ev.preventDefault()
|
||||
const hit = hitRow(ev.clientX, ev.clientY)
|
||||
// 只认同一周期组的落点
|
||||
if (hit && hit.id !== s.item.id) { s.over = hit; setOver(hit) }
|
||||
else { s.over = null; setOver(null) }
|
||||
}
|
||||
|
||||
const onUp = () => {
|
||||
const s = st.current
|
||||
if (s.active && s.item) {
|
||||
lastEnd.current = Date.now()
|
||||
if (s.over && s.over.id !== s.item.id) onDrop?.(s.item, s.over.id, s.over.after)
|
||||
}
|
||||
cleanup()
|
||||
}
|
||||
|
||||
/** 绑定到卡片: 卡片元素需设置 touch-action: pan-y */
|
||||
const bind = useCallback((item) => ({
|
||||
onPointerDown: (ev) => {
|
||||
if (ev.button !== undefined && ev.button !== 0) return
|
||||
st.current = { ...st.current, startX: ev.clientX, startY: ev.clientY, item, active: false }
|
||||
st.current.timer = setTimeout(() => {
|
||||
st.current.active = true
|
||||
setDragItem(item)
|
||||
if (navigator.vibrate) navigator.vibrate(15)
|
||||
}, 400)
|
||||
try { ev.currentTarget.setPointerCapture(ev.pointerId) } catch { /* ignore */ }
|
||||
const el = ev.currentTarget
|
||||
const move = (e2) => onMove(e2)
|
||||
const tm = (e2) => { if (st.current.active) e2.preventDefault() }
|
||||
const up = () => { onUp(); detach() }
|
||||
const cancel = () => {
|
||||
if (st.current.active) lastEnd.current = Date.now()
|
||||
cleanup()
|
||||
detach()
|
||||
}
|
||||
const detach = () => {
|
||||
el.removeEventListener('pointermove', move)
|
||||
el.removeEventListener('pointerup', up)
|
||||
el.removeEventListener('pointercancel', cancel)
|
||||
el.removeEventListener('touchmove', tm)
|
||||
}
|
||||
el.addEventListener('pointermove', move)
|
||||
el.addEventListener('pointerup', up)
|
||||
el.addEventListener('pointercancel', cancel)
|
||||
el.addEventListener('touchmove', tm, { passive: false })
|
||||
},
|
||||
onContextMenu: (ev) => ev.preventDefault(),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}), [])
|
||||
|
||||
return { dragItem, over, bind, cancel: cleanup, justEnded }
|
||||
}
|
||||
@@ -99,6 +99,8 @@ export default function useColumnDrag({ onDrop, scrollSelector = '.board-wrap' }
|
||||
try { ev.currentTarget.setPointerCapture(ev.pointerId) } catch { /* ignore */ }
|
||||
const el = ev.currentTarget
|
||||
const move = (e2) => onPointerMove(e2)
|
||||
// 激活后拦截触摸滚动: 防纵向分量触发浏览器接管 (pointercancel), 同 useRowDrag
|
||||
const tm = (e2) => { if (st.current.active) e2.preventDefault() }
|
||||
const up = (e2) => { onPointerUp(e2); detach() }
|
||||
const cancel = () => {
|
||||
if (st.current.active) lastEnd.current = Date.now()
|
||||
@@ -109,10 +111,12 @@ export default function useColumnDrag({ onDrop, scrollSelector = '.board-wrap' }
|
||||
el.removeEventListener('pointermove', move)
|
||||
el.removeEventListener('pointerup', up)
|
||||
el.removeEventListener('pointercancel', cancel)
|
||||
el.removeEventListener('touchmove', tm)
|
||||
}
|
||||
el.addEventListener('pointermove', move)
|
||||
el.addEventListener('pointerup', up)
|
||||
el.addEventListener('pointercancel', cancel)
|
||||
el.addEventListener('touchmove', tm, { passive: false })
|
||||
},
|
||||
// 长按不弹系统菜单 (配合 CSS user-select:none, 防长按变文字选择)
|
||||
onContextMenu: (ev) => ev.preventDefault(),
|
||||
|
||||
@@ -74,6 +74,10 @@ export default function useRowDrag({ columns, onDrop }) {
|
||||
try { ev.currentTarget.setPointerCapture(ev.pointerId) } catch { /* ignore */ }
|
||||
const el = ev.currentTarget
|
||||
const move = (e2) => onMove(e2)
|
||||
// 激活后拦截触摸滚动: pan-y 下纵向分量稍大浏览器即接管手势并派发
|
||||
// pointercancel (列表是整页长滚动容器, 必现), 非 passive touchmove
|
||||
// preventDefault 才能真正拦住, 拖动期间指针事件得以持续派发
|
||||
const tm = (e2) => { if (st.current.active) e2.preventDefault() }
|
||||
const up = () => { onUp(); detach() }
|
||||
const cancel = () => {
|
||||
if (st.current.active) lastEnd.current = Date.now()
|
||||
@@ -84,10 +88,12 @@ export default function useRowDrag({ columns, onDrop }) {
|
||||
el.removeEventListener('pointermove', move)
|
||||
el.removeEventListener('pointerup', up)
|
||||
el.removeEventListener('pointercancel', cancel)
|
||||
el.removeEventListener('touchmove', tm)
|
||||
}
|
||||
el.addEventListener('pointermove', move)
|
||||
el.addEventListener('pointerup', up)
|
||||
el.addEventListener('pointercancel', cancel)
|
||||
el.addEventListener('touchmove', tm, { passive: false })
|
||||
},
|
||||
// 长按不弹系统菜单 (配合 CSS user-select:none, 防长按变文字选择)
|
||||
onContextMenu: (ev) => ev.preventDefault(),
|
||||
|
||||
+338
-282
@@ -1,282 +1,338 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
Button, Dialog, DotLoading, Empty, Input, Popup, Selector, Stepper, Toast,
|
||||
} from 'antd-mobile'
|
||||
import RingProgress, { Celebrate } from '../../components/RingProgress.jsx'
|
||||
import { checkinApi } from '../../api/checkin.js'
|
||||
import useRefreshOnVisible from '../../hooks/useRefreshOnVisible.js'
|
||||
import { toDateStr, dayLabel } from './date.js'
|
||||
|
||||
const PERIOD_OPTIONS = [
|
||||
{ label: '每天', value: 'day' },
|
||||
{ label: '每周', value: 'week' },
|
||||
{ label: '每月', value: 'month' },
|
||||
{ label: '每年', value: 'year' },
|
||||
]
|
||||
|
||||
const COLORS = ['#1677ff', '#00b578', '#ff8f1f', '#ff3141', '#a855f7', '#14b8a6', '#f43f9e']
|
||||
|
||||
const EMPTY_FORM = { id: null, name: '', period: 'day', target: 1, color: COLORS[0], note: '' }
|
||||
|
||||
// 打卡视图: 今日待办列表 + 环形进度 + 打卡/撤销 + 新建/编辑
|
||||
export default function HabitView({ date, onDateChange }) {
|
||||
const [data, setData] = useState(null) // { today, date, items, summary }
|
||||
const [err, setErr] = useState('')
|
||||
const [bursts, setBursts] = useState({}) // { habitId: 触发计数 }
|
||||
const [form, setForm] = useState(EMPTY_FORM)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
|
||||
const load = useCallback((silent) => {
|
||||
if (!silent) setErr('')
|
||||
checkinApi.habits(date)
|
||||
.then((d) => setData(d))
|
||||
.catch((e) => { if (!silent) setErr(e.message) })
|
||||
}, [date])
|
||||
|
||||
useEffect(() => { load(false) }, [load])
|
||||
useRefreshOnVisible(() => load(true))
|
||||
|
||||
const items = useMemo(() => {
|
||||
const list = data?.items || []
|
||||
// 未完成在前, 已完成在后 (F-CK-16 默认排序)
|
||||
return [...list].sort((a, b) => Number(a.completed) - Number(b.completed) || a.id - b.id)
|
||||
}, [data])
|
||||
|
||||
const fireBurst = (id) => setBursts((m) => ({ ...m, [id]: (m[id] || 0) + 1 }))
|
||||
|
||||
// 乐观更新: 先本地 +1, 成功用服务端结果覆盖, 失败回滚 (F-SY-06/E-02)
|
||||
async function doCheck(item) {
|
||||
const before = data
|
||||
const patch = (it) => {
|
||||
const done = it.done + 1
|
||||
return {
|
||||
...it,
|
||||
done,
|
||||
remaining: Math.max(0, it.target - done),
|
||||
percent: Math.min(1, done / it.target),
|
||||
completed: done >= it.target,
|
||||
over: Math.max(0, done - it.target),
|
||||
countOnDate: (it.countOnDate || 0) + 1,
|
||||
dayDone: (it.countOnDate || 0) + 1 >= it.expectedPerDay,
|
||||
}
|
||||
}
|
||||
setData((d) => ({ ...d, items: d.items.map((x) => (x.id === item.id ? patch(x) : x)) }))
|
||||
try {
|
||||
const res = await checkinApi.check(item.id, date)
|
||||
setData((d) => ({ ...d, items: d.items.map((x) => (x.id === item.id ? res.item : x)) }))
|
||||
if (res.item.completed) fireBurst(item.id)
|
||||
} catch (e) {
|
||||
setData(before)
|
||||
Toast.show({ content: e.message || '打卡失败' })
|
||||
}
|
||||
}
|
||||
|
||||
async function doUncheck(item) {
|
||||
const before = data
|
||||
setData((d) => ({
|
||||
...d,
|
||||
items: d.items.map((x) => {
|
||||
if (x.id !== item.id) return x
|
||||
const done = Math.max(0, x.done - 1)
|
||||
return {
|
||||
...x,
|
||||
done,
|
||||
remaining: Math.max(0, x.target - done),
|
||||
percent: Math.min(1, done / x.target),
|
||||
completed: done >= x.target,
|
||||
over: Math.max(0, done - x.target),
|
||||
countOnDate: Math.max(0, (x.countOnDate || 0) - 1),
|
||||
}
|
||||
}),
|
||||
}))
|
||||
try {
|
||||
const res = await checkinApi.uncheck(item.id, date)
|
||||
setData((d) => ({ ...d, items: d.items.map((x) => (x.id === item.id ? res.item : x)) }))
|
||||
} catch (e) {
|
||||
setData(before)
|
||||
Toast.show({ content: e.message || '撤销失败' })
|
||||
}
|
||||
}
|
||||
|
||||
async function submitForm() {
|
||||
const name = String(form.name || '').trim()
|
||||
if (!name) return Toast.show({ content: '请填写名称' })
|
||||
if (name.length > 20) return Toast.show({ content: '名称不能超过 20 个字' })
|
||||
const payload = { name, period: form.period, target: Number(form.target) || 1, color: form.color, note: form.note }
|
||||
try {
|
||||
if (form.id) await checkinApi.updateHabit(form.id, payload)
|
||||
else await checkinApi.createHabit(payload)
|
||||
setShowForm(false)
|
||||
setForm(EMPTY_FORM)
|
||||
load(true)
|
||||
} catch (e) {
|
||||
Toast.show({ content: e.message || '保存失败' })
|
||||
}
|
||||
}
|
||||
|
||||
async function removeHabit(item) {
|
||||
const ok = await Dialog.confirm({
|
||||
content: `归档「${item.name}」?归档后不再出现在待办,历史记录保留。`,
|
||||
confirmText: '归档',
|
||||
cancelText: '取消',
|
||||
})
|
||||
if (!ok) return
|
||||
try {
|
||||
await checkinApi.deleteHabit(item.id)
|
||||
Toast.show({ content: '已归档' })
|
||||
load(true)
|
||||
} catch (e) {
|
||||
Toast.show({ content: e.message || '操作失败' })
|
||||
}
|
||||
}
|
||||
|
||||
const summary = data?.summary || { total: 0, done: 0 }
|
||||
const isToday = data ? data.date === data.today : true
|
||||
|
||||
return (
|
||||
<div className="habit-view">
|
||||
<div className="habit-head">
|
||||
<div className="habit-head-left">
|
||||
<div className="habit-date">{dayLabel(date, data?.today || toDateStr())}</div>
|
||||
<div className="habit-summary">
|
||||
已完成 <strong>{summary.done}</strong> / {summary.total}
|
||||
{!isToday && <span className="habit-badge">非今天</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="habit-head-right">
|
||||
<Button size="mini" color="primary" onClick={() => { setForm(EMPTY_FORM); setShowForm(true) }}>
|
||||
+ 新建
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{err && (
|
||||
<div className="error-banner">
|
||||
{err}
|
||||
<span className="retry-link" onClick={() => load(false)}>重试</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data === null && !err && <div className="monitor-loading"><DotLoading /> 加载中...</div>}
|
||||
|
||||
{data !== null && !err && items.length === 0 && (
|
||||
<div className="checkin-empty">
|
||||
<Empty description="还没有打卡项" />
|
||||
<Button color="primary" size="small" onClick={() => { setForm(EMPTY_FORM); setShowForm(true) }}>
|
||||
创建第一个打卡项
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="habit-list">
|
||||
{items.map((item) => (
|
||||
<div key={item.id} className={'habit-card' + (item.completed ? ' done' : '')}>
|
||||
<RingProgress
|
||||
percent={item.percent}
|
||||
done={item.done}
|
||||
target={item.target}
|
||||
over={item.over}
|
||||
completed={item.completed}
|
||||
color={item.color}
|
||||
onClick={() => doCheck(item)}
|
||||
/>
|
||||
<div className="habit-main">
|
||||
<div className="habit-name">{item.name}</div>
|
||||
<div className="habit-meta">
|
||||
{item.periodLabel} {item.target} 次
|
||||
{item.streak > 0 && <span className="habit-streak">连续 {item.streak}</span>}
|
||||
</div>
|
||||
{item.note && <div className="habit-note">{item.note}</div>}
|
||||
<div className="habit-range">
|
||||
{item.periodStart === item.periodEnd
|
||||
? '今日'
|
||||
: `${item.periodStart.slice(5)} ~ ${item.periodEnd.slice(5)}`}
|
||||
{item.over > 0 && <span className="habit-over">超额 {item.over}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="habit-actions">
|
||||
<Button
|
||||
size="mini"
|
||||
color={item.completed ? 'default' : 'primary'}
|
||||
onClick={() => doCheck(item)}
|
||||
>
|
||||
{item.completed ? '再打一次' : '打卡'}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="habit-foot">
|
||||
{item.done > 0 && (
|
||||
<span className="habit-link" onClick={() => doUncheck(item)}>撤销</span>
|
||||
)}
|
||||
<span
|
||||
className="habit-link"
|
||||
onClick={() => {
|
||||
setForm({ id: item.id, name: item.name, period: item.period, target: item.target, color: item.color, note: item.note })
|
||||
setShowForm(true)
|
||||
}}
|
||||
>编辑</span>
|
||||
<span className="habit-link danger" onClick={() => removeHabit(item)}>归档</span>
|
||||
</div>
|
||||
<Celebrate fire={bursts[item.id] || 0} color={item.color} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 新建 / 编辑 */}
|
||||
<Popup
|
||||
visible={showForm}
|
||||
onMaskClick={() => setShowForm(false)}
|
||||
bodyStyle={{ borderTopLeftRadius: 12, borderTopRightRadius: 12, paddingBottom: 16 }}
|
||||
>
|
||||
<div className="form-popup">
|
||||
<div className="form-title">{form.id ? '编辑打卡项' : '新建打卡项'}</div>
|
||||
<div className="form-field">
|
||||
<label>名称</label>
|
||||
<Input
|
||||
placeholder="例如:喝水 / 健身 / 读书"
|
||||
value={form.name}
|
||||
maxLength={20}
|
||||
onChange={(v) => setForm((f) => ({ ...f, name: v }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>周期</label>
|
||||
<Selector
|
||||
options={PERIOD_OPTIONS}
|
||||
value={[form.period]}
|
||||
onChange={(v) => setForm((f) => ({ ...f, period: v[0] }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>目标次数(周期内)</label>
|
||||
<Stepper min={1} max={999} value={form.target} onChange={(v) => setForm((f) => ({ ...f, target: v }))} />
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>颜色</label>
|
||||
<div className="color-row">
|
||||
{COLORS.map((c) => (
|
||||
<span
|
||||
key={c}
|
||||
className={'color-dot' + (form.color === c ? ' active' : '')}
|
||||
style={{ background: c }}
|
||||
onClick={() => setForm((f) => ({ ...f, color: c }))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>备注(可选)</label>
|
||||
<Input
|
||||
placeholder="补充说明"
|
||||
value={form.note}
|
||||
onChange={(v) => setForm((f) => ({ ...f, note: v }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-actions">
|
||||
<Button block color="primary" onClick={submitForm}>保存</Button>
|
||||
<Button block fill="outline" onClick={() => setShowForm(false)} style={{ marginTop: 8 }}>取消</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Popup>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
Button, Dialog, DotLoading, Empty, Input, Popup, Selector, Stepper, Toast,
|
||||
} from 'antd-mobile'
|
||||
import RingProgress, { Celebrate } from '../../components/RingProgress.jsx'
|
||||
import useHabitDrag from '../../components/checkin/useHabitDrag.js'
|
||||
import { checkinApi } from '../../api/checkin.js'
|
||||
import useRefreshOnVisible from '../../hooks/useRefreshOnVisible.js'
|
||||
import { toDateStr, dayLabel } from './date.js'
|
||||
|
||||
const PERIOD_OPTIONS = [
|
||||
{ label: '每天', value: 'day' },
|
||||
{ label: '每周', value: 'week' },
|
||||
{ label: '每月', value: 'month' },
|
||||
{ label: '每年', value: 'year' },
|
||||
]
|
||||
|
||||
const COLORS = ['#1677ff', '#00b578', '#ff8f1f', '#ff3141', '#a855f7', '#14b8a6', '#f43f9e']
|
||||
|
||||
const EMPTY_FORM = { id: null, name: '', period: 'day', target: 1, color: COLORS[0], note: '' }
|
||||
|
||||
// 打卡视图: 今日待办列表 + 环形进度 + 打卡/撤销 + 新建/编辑
|
||||
export default function HabitView({ date, onDateChange }) {
|
||||
const [data, setData] = useState(null) // { today, date, items, summary }
|
||||
const [err, setErr] = useState('')
|
||||
const [bursts, setBursts] = useState({}) // { habitId: 触发计数 }
|
||||
const [form, setForm] = useState(EMPTY_FORM)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
|
||||
const load = useCallback((silent) => {
|
||||
if (!silent) setErr('')
|
||||
checkinApi.habits(date)
|
||||
.then((d) => setData(d))
|
||||
.catch((e) => { if (!silent) setErr(e.message) })
|
||||
}, [date])
|
||||
|
||||
useEffect(() => { load(false) }, [load])
|
||||
useRefreshOnVisible(() => load(true))
|
||||
|
||||
const items = useMemo(() => {
|
||||
const list = data?.items || []
|
||||
// 手动排序优先 (sortOrder), 拖动排序后覆盖 F-CK-16 的"未完成在前"
|
||||
return [...list].sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0) || a.id - b.id)
|
||||
}, [data])
|
||||
|
||||
// 按周期分组 (每天/每周/每月/每年), 组内顺序 = 手动排序
|
||||
const groups = useMemo(() => {
|
||||
const out = []
|
||||
for (const p of PERIOD_OPTIONS) {
|
||||
const list = items.filter((i) => i.period === p.value)
|
||||
if (list.length) out.push({ key: p.value, label: p.label, list })
|
||||
}
|
||||
const known = new Set(PERIOD_OPTIONS.map((p) => p.value))
|
||||
const rest = items.filter((i) => !known.has(i.period))
|
||||
if (rest.length) out.push({ key: 'other', label: '其他', list: rest })
|
||||
return out
|
||||
}, [items])
|
||||
|
||||
const drag = useHabitDrag({ onDrop: reorderHabit })
|
||||
|
||||
// 组内拖动落位: 重排后按展平顺序整体重写 sortOrder
|
||||
async function reorderHabit(dragged, targetId, after) {
|
||||
const snapshot = data
|
||||
const g = groups.find((x) => x.key === dragged.period)
|
||||
if (!g) return
|
||||
const rest = g.list.filter((i) => i.id !== dragged.id)
|
||||
const ti = rest.findIndex((i) => i.id === targetId)
|
||||
if (ti < 0) return
|
||||
rest.splice(after ? ti + 1 : ti, 0, dragged)
|
||||
const flat = groups.map((x) => (x.key === g.key ? rest : x.list)).flat()
|
||||
const withOrder = flat.map((it, i) => ({ ...it, sortOrder: i }))
|
||||
setData((d) => ({ ...d, items: withOrder }))
|
||||
try {
|
||||
await checkinApi.reorderHabits(flat.map((i) => i.id))
|
||||
} catch (e) {
|
||||
setData(snapshot)
|
||||
Toast.show({ content: e.message || '排序保存失败' })
|
||||
}
|
||||
}
|
||||
|
||||
const fireBurst = (id) => setBursts((m) => ({ ...m, [id]: (m[id] || 0) + 1 }))
|
||||
|
||||
// 乐观更新: 先本地 +1, 成功用服务端结果覆盖, 失败回滚 (F-SY-06/E-02)
|
||||
async function doCheck(item) {
|
||||
const before = data
|
||||
const patch = (it) => {
|
||||
const done = it.done + 1
|
||||
return {
|
||||
...it,
|
||||
done,
|
||||
remaining: Math.max(0, it.target - done),
|
||||
percent: Math.min(1, done / it.target),
|
||||
completed: done >= it.target,
|
||||
over: Math.max(0, done - it.target),
|
||||
countOnDate: (it.countOnDate || 0) + 1,
|
||||
dayDone: (it.countOnDate || 0) + 1 >= it.expectedPerDay,
|
||||
}
|
||||
}
|
||||
setData((d) => ({ ...d, items: d.items.map((x) => (x.id === item.id ? patch(x) : x)) }))
|
||||
try {
|
||||
const res = await checkinApi.check(item.id, date)
|
||||
setData((d) => ({ ...d, items: d.items.map((x) => (x.id === item.id ? res.item : x)) }))
|
||||
if (res.item.completed) fireBurst(item.id)
|
||||
} catch (e) {
|
||||
setData(before)
|
||||
Toast.show({ content: e.message || '打卡失败' })
|
||||
}
|
||||
}
|
||||
|
||||
async function doUncheck(item) {
|
||||
const before = data
|
||||
setData((d) => ({
|
||||
...d,
|
||||
items: d.items.map((x) => {
|
||||
if (x.id !== item.id) return x
|
||||
const done = Math.max(0, x.done - 1)
|
||||
return {
|
||||
...x,
|
||||
done,
|
||||
remaining: Math.max(0, x.target - done),
|
||||
percent: Math.min(1, done / x.target),
|
||||
completed: done >= x.target,
|
||||
over: Math.max(0, done - x.target),
|
||||
countOnDate: Math.max(0, (x.countOnDate || 0) - 1),
|
||||
}
|
||||
}),
|
||||
}))
|
||||
try {
|
||||
const res = await checkinApi.uncheck(item.id, date)
|
||||
setData((d) => ({ ...d, items: d.items.map((x) => (x.id === item.id ? res.item : x)) }))
|
||||
} catch (e) {
|
||||
setData(before)
|
||||
Toast.show({ content: e.message || '撤销失败' })
|
||||
}
|
||||
}
|
||||
|
||||
async function submitForm() {
|
||||
const name = String(form.name || '').trim()
|
||||
if (!name) return Toast.show({ content: '请填写名称' })
|
||||
if (name.length > 20) return Toast.show({ content: '名称不能超过 20 个字' })
|
||||
const payload = { name, period: form.period, target: Number(form.target) || 1, color: form.color, note: form.note }
|
||||
try {
|
||||
if (form.id) await checkinApi.updateHabit(form.id, payload)
|
||||
else await checkinApi.createHabit(payload)
|
||||
setShowForm(false)
|
||||
setForm(EMPTY_FORM)
|
||||
load(true)
|
||||
} catch (e) {
|
||||
Toast.show({ content: e.message || '保存失败' })
|
||||
}
|
||||
}
|
||||
|
||||
async function removeHabit(item) {
|
||||
const ok = await Dialog.confirm({
|
||||
content: `归档「${item.name}」?归档后不再出现在待办,历史记录保留。`,
|
||||
confirmText: '归档',
|
||||
cancelText: '取消',
|
||||
})
|
||||
if (!ok) return
|
||||
try {
|
||||
await checkinApi.deleteHabit(item.id)
|
||||
Toast.show({ content: '已归档' })
|
||||
load(true)
|
||||
} catch (e) {
|
||||
Toast.show({ content: e.message || '操作失败' })
|
||||
}
|
||||
}
|
||||
|
||||
const summary = data?.summary || { total: 0, done: 0 }
|
||||
const isToday = data ? data.date === data.today : true
|
||||
|
||||
return (
|
||||
<div className="habit-view">
|
||||
<div className="habit-head">
|
||||
<div className="habit-head-left">
|
||||
<div className="habit-date">{dayLabel(date, data?.today || toDateStr())}</div>
|
||||
<div className="habit-summary">
|
||||
已完成 <strong>{summary.done}</strong> / {summary.total}
|
||||
{!isToday && <span className="habit-badge">非今天</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="habit-head-right">
|
||||
<Button size="mini" color="primary" onClick={() => { setForm(EMPTY_FORM); setShowForm(true) }}>
|
||||
+ 新建
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{err && (
|
||||
<div className="error-banner">
|
||||
{err}
|
||||
<span className="retry-link" onClick={() => load(false)}>重试</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data === null && !err && <div className="monitor-loading"><DotLoading /> 加载中...</div>}
|
||||
|
||||
{data !== null && !err && items.length === 0 && (
|
||||
<div className="checkin-empty">
|
||||
<Empty description="还没有打卡项" />
|
||||
<Button color="primary" size="small" onClick={() => { setForm(EMPTY_FORM); setShowForm(true) }}>
|
||||
创建第一个打卡项
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="habit-list">
|
||||
{groups.map((g) => (
|
||||
<div key={g.key}>
|
||||
<div className="habit-group-title">
|
||||
{g.label}
|
||||
<span className="cnt">{g.list.length}</span>
|
||||
</div>
|
||||
{g.list.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
data-habit-row
|
||||
data-habit-id={item.id}
|
||||
className={
|
||||
'habit-card'
|
||||
+ (item.completed ? ' done' : '')
|
||||
+ (drag.dragItem?.id === item.id ? ' dragging' : '')
|
||||
+ (drag.over?.id === item.id ? ` dragover ${drag.over.after ? 'after' : 'before'}` : '')
|
||||
}
|
||||
{...drag.bind(item)}
|
||||
>
|
||||
<RingProgress
|
||||
percent={item.percent}
|
||||
done={item.done}
|
||||
target={item.target}
|
||||
over={item.over}
|
||||
completed={item.completed}
|
||||
color={item.color}
|
||||
onClick={() => { if (!drag.justEnded()) doCheck(item) }}
|
||||
/>
|
||||
<div className="habit-main">
|
||||
<div className="habit-name">{item.name}</div>
|
||||
<div className="habit-meta">
|
||||
{item.periodLabel} {item.target} 次
|
||||
{item.streak > 0 && <span className="habit-streak">连续 {item.streak}</span>}
|
||||
</div>
|
||||
{item.note && <div className="habit-note">{item.note}</div>}
|
||||
<div className="habit-range">
|
||||
{item.periodStart === item.periodEnd
|
||||
? '今日'
|
||||
: `${item.periodStart.slice(5)} ~ ${item.periodEnd.slice(5)}`}
|
||||
{item.over > 0 && <span className="habit-over">超额 {item.over}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="habit-actions">
|
||||
<Button
|
||||
size="mini"
|
||||
color={item.completed ? 'default' : 'primary'}
|
||||
onClick={() => { if (!drag.justEnded()) doCheck(item) }}
|
||||
>
|
||||
{item.completed ? '再打一次' : '打卡'}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="habit-foot">
|
||||
{item.done > 0 && (
|
||||
<span className="habit-link" onClick={() => { if (!drag.justEnded()) doUncheck(item) }}>撤销</span>
|
||||
)}
|
||||
<span
|
||||
className="habit-link"
|
||||
onClick={() => {
|
||||
if (drag.justEnded()) return
|
||||
setForm({ id: item.id, name: item.name, period: item.period, target: item.target, color: item.color, note: item.note })
|
||||
setShowForm(true)
|
||||
}}
|
||||
>编辑</span>
|
||||
<span className="habit-link danger" onClick={() => { if (!drag.justEnded()) removeHabit(item) }}>归档</span>
|
||||
</div>
|
||||
<Celebrate fire={bursts[item.id] || 0} color={item.color} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 新建 / 编辑 */}
|
||||
<Popup
|
||||
visible={showForm}
|
||||
onMaskClick={() => setShowForm(false)}
|
||||
bodyStyle={{ borderTopLeftRadius: 12, borderTopRightRadius: 12, paddingBottom: 16 }}
|
||||
>
|
||||
<div className="form-popup">
|
||||
<div className="form-title">{form.id ? '编辑打卡项' : '新建打卡项'}</div>
|
||||
<div className="form-field">
|
||||
<label>名称</label>
|
||||
<Input
|
||||
placeholder="例如:喝水 / 健身 / 读书"
|
||||
value={form.name}
|
||||
maxLength={20}
|
||||
onChange={(v) => setForm((f) => ({ ...f, name: v }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>周期</label>
|
||||
<Selector
|
||||
options={PERIOD_OPTIONS}
|
||||
value={[form.period]}
|
||||
onChange={(v) => setForm((f) => ({ ...f, period: v[0] }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>目标次数(周期内)</label>
|
||||
<Stepper min={1} max={999} value={form.target} onChange={(v) => setForm((f) => ({ ...f, target: v }))} />
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>颜色</label>
|
||||
<div className="color-row">
|
||||
{COLORS.map((c) => (
|
||||
<span
|
||||
key={c}
|
||||
className={'color-dot' + (form.color === c ? ' active' : '')}
|
||||
style={{ background: c }}
|
||||
onClick={() => setForm((f) => ({ ...f, color: c }))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>备注(可选)</label>
|
||||
<Input
|
||||
placeholder="补充说明"
|
||||
value={form.note}
|
||||
onChange={(v) => setForm((f) => ({ ...f, note: v }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-actions">
|
||||
<Button block color="primary" onClick={submitForm}>保存</Button>
|
||||
<Button block fill="outline" onClick={() => setShowForm(false)} style={{ marginTop: 8 }}>取消</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Popup>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -663,6 +663,21 @@ body.me-safe-top .app-safe-top { height: 0; }
|
||||
.habit-link { font-size: 12px; color: var(--color-primary); cursor: pointer; }
|
||||
.habit-link.danger { color: var(--color-danger); }
|
||||
|
||||
/* 打卡项分组 + 长按拖动排序 (组内) */
|
||||
.habit-view { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
|
||||
.habit-view input, .habit-view textarea { -webkit-user-select: text; user-select: text; }
|
||||
.habit-group-title {
|
||||
display: flex; align-items: center; gap: 7px; padding: 10px 2px 4px;
|
||||
font-size: 12px; color: var(--color-muted); font-weight: 600;
|
||||
}
|
||||
.habit-group-title::before { content: ""; width: 3px; height: 12px; border-radius: 2px; background: var(--color-primary); }
|
||||
.habit-group-title .cnt { color: #b8bcc4; font-weight: 400; }
|
||||
.habit-card { touch-action: pan-y; }
|
||||
.habit-card.dragging { opacity: 0.55; outline: 2px dashed var(--color-primary); outline-offset: 1px; }
|
||||
.habit-card.dragover { outline: 2px solid var(--color-primary); outline-offset: 1px; }
|
||||
.habit-card.dragover.after { border-bottom: 3px solid var(--color-primary); }
|
||||
.habit-card.dragover.before { border-top: 3px solid var(--color-primary); }
|
||||
|
||||
/* ----- 日历视图 ----- */
|
||||
.calendar-view { padding: 0 12px 20px; }
|
||||
.cal-month-bar { display: flex; align-items: center; gap: 10px; padding: 8px 2px; }
|
||||
|
||||
Reference in New Issue
Block a user