Files
XCDesktop/api/modules/todo/parser.ts
2026-03-08 01:34:54 +08:00

52 lines
1.4 KiB
TypeScript

import type { TodoItem, DayTodo } from './types.js'
export const parseTodoContent = (content: string): DayTodo[] => {
const lines = content.split('\n')
const result: DayTodo[] = []
let currentDate: string | null = null
let currentItems: TodoItem[] = []
let itemId = 0
for (const line of lines) {
const dateMatch = line.match(/^##\s*(\d{4}-\d{2}-\d{2})/)
if (dateMatch) {
if (currentDate) {
result.push({ date: currentDate, items: currentItems })
}
currentDate = dateMatch[1]
currentItems = []
} else if (currentDate) {
const todoMatch = line.match(/^- (√|○) (.*)$/)
if (todoMatch) {
currentItems.push({
id: `${currentDate}-${itemId++}`,
content: todoMatch[2],
completed: todoMatch[1] === '√'
})
}
}
}
if (currentDate) {
result.push({ date: currentDate, items: currentItems })
}
return result
}
export const generateTodoContent = (dayTodos: DayTodo[]): string => {
const lines: string[] = []
const sortedDays = [...dayTodos].sort((a, b) => a.date.localeCompare(b.date))
for (const day of sortedDays) {
lines.push(`## ${day.date}`)
for (const item of day.items) {
const checkbox = item.completed ? '√' : '○'
lines.push(`- ${checkbox} ${item.content}`)
}
lines.push('')
}
return lines.join('\n').trimEnd()
}