richer editing

This commit is contained in:
2025-08-15 00:13:38 -04:00
parent 5dfd38e5a5
commit 238d3cfbfe
3 changed files with 182 additions and 46 deletions

View File

@@ -5,20 +5,26 @@ import { nanoid } from 'nanoid'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { type CalendarEvent } from '@/lib/types'
import { addEvent, deleteEvent, getAllEvents, clearEvents, getDB } from '@/lib/db'
import { parseICS, generateICS } from '@/lib/ical'
import type { CalendarEvent } from '@/lib/types'
export default function HomePage() {
const [events, setEvents] = useState<CalendarEvent[]>([])
const [dialogOpen, setDialogOpen] = useState(false)
const [title, setTitle] = useState('')
const [start, setStart] = useState('')
const [editingId, setEditingId] = useState<string | null>(null)
const [isDragOver, setIsDragOver] = useState(false)
// Load events only in the browser
// Form fields
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [location, setLocation] = useState('')
const [url, setUrl] = useState('')
const [start, setStart] = useState('')
const [end, setEnd] = useState('')
const [allDay, setAllDay] = useState(false)
useEffect(() => {
(async () => {
const stored = await getAllEvents()
@@ -28,24 +34,40 @@ export default function HomePage() {
const resetForm = () => {
setTitle('')
setDescription('')
setLocation('')
setUrl('')
setStart('')
setEnd('')
setAllDay(false)
setEditingId(null)
}
const handleSave = async () => {
const eventData: CalendarEvent = {
id: editingId || nanoid(),
title,
description,
location,
url,
start,
end: end || undefined,
allDay,
createdAt: editingId
? events.find(e => e.id === editingId)?.createdAt
: new Date().toISOString(),
lastModified: new Date().toISOString(),
}
if (editingId) {
// EDIT EXISTING
const updatedEvent = { id: editingId, title, start }
const db = await getDB()
if (db) {
await db.put('events', updatedEvent)
setEvents(prev => prev.map(e => (e.id === editingId ? updatedEvent : e)))
await db.put('events', eventData)
setEvents(prev => prev.map(e => (e.id === editingId ? eventData : e)))
}
} else {
// ADD NEW
const newEvent = { id: nanoid(), title, start }
await addEvent(newEvent)
setEvents(prev => [...prev, newEvent])
await addEvent(eventData)
setEvents(prev => [...prev, eventData])
}
resetForm()
setDialogOpen(false)
@@ -61,11 +83,9 @@ export default function HomePage() {
setEvents([])
}
// --- IMPORT ---
const handleImport = async (file: File) => {
const text = await file.text()
const parsed = parseICS(text)
for (const ev of parsed) {
await addEvent(ev)
}
@@ -73,7 +93,6 @@ export default function HomePage() {
setEvents(stored)
}
// --- EXPORT ---
const handleExport = () => {
const icsData = generateICS(events)
const blob = new Blob([icsData], { type: 'text/calendar' })
@@ -87,17 +106,15 @@ export default function HomePage() {
URL.revokeObjectURL(url)
}
// --- DRAG & DROP ---
// Drag & drop
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault()
setIsDragOver(true)
}
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault()
setIsDragOver(false)
}
const handleDrop = (e: React.DragEvent) => {
e.preventDefault()
setIsDragOver(false)
@@ -123,8 +140,12 @@ export default function HomePage() {
<Button onClick={() => setDialogOpen(true)}>Add Event</Button>
{events.length > 0 && (
<>
<Button variant="secondary" onClick={handleExport}>Export .ics</Button>
<Button variant="destructive" onClick={handleClearAll}>Clear All</Button>
<Button variant="secondary" onClick={handleExport}>
Export .ics
</Button>
<Button variant="destructive" onClick={handleClearAll}>
Clear All
</Button>
</>
)}
<label className="cursor-pointer">
@@ -153,15 +174,28 @@ export default function HomePage() {
className="border p-2 rounded bg-white shadow-sm flex justify-between items-center"
>
<div>
<strong>{ev.title}</strong> {ev.start}
<strong>{ev.title}</strong> {ev.allDay
? ev.start.split('T')[0]
: new Date(ev.start).toLocaleString()}
{ev.location && <div className="text-sm text-gray-500">{ev.location}</div>}
</div>
<div className="flex gap-2">
<Button size="sm" onClick={() => {
<Button
size="sm"
onClick={() => {
setTitle(ev.title)
setDescription(ev.description || '')
setLocation(ev.location || '')
setUrl(ev.url || '')
setStart(ev.start)
setEnd(ev.end || '')
setAllDay(ev.allDay || false)
setEditingId(ev.id)
setDialogOpen(true)
}}>Edit</Button>
}}
>
Edit
</Button>
<Button variant="secondary" size="sm" onClick={() => handleDelete(ev.id)}>
Delete
</Button>
@@ -170,16 +204,56 @@ export default function HomePage() {
))}
</ul>
<Dialog open={dialogOpen} onOpenChange={(val) => {
<Dialog
open={dialogOpen}
onOpenChange={val => {
if (!val) resetForm()
setDialogOpen(val)
}}>
<DialogContent>
}}
>
<DialogContent className="space-y-2">
<DialogHeader>
<DialogTitle>{editingId ? 'Edit Event' : 'Add Event'}</DialogTitle>
</DialogHeader>
<Input placeholder="Title" value={title} onChange={e => setTitle(e.target.value)} />
<Input type="date" value={start} onChange={e => setStart(e.target.value)} />
<textarea
className="border p-2 rounded w-full"
placeholder="Description"
value={description}
onChange={e => setDescription(e.target.value)}
></textarea>
<Input placeholder="Location" value={location} onChange={e => setLocation(e.target.value)} />
<Input placeholder="URL" value={url} onChange={e => setUrl(e.target.value)} />
<label className="flex items-center gap-2 mt-2">
<input type="checkbox" checked={allDay} onChange={e => setAllDay(e.target.checked)} />
All day event
</label>
{!allDay && (
<>
<label>Start date & time</label>
<Input type="datetime-local" value={start} onChange={e => setStart(e.target.value)} />
<label>End date & time</label>
<Input type="datetime-local" value={end} onChange={e => setEnd(e.target.value)} />
</>
)}
{allDay && (
<>
<label>Start date</label>
<Input
type="date"
value={start ? start.split('T')[0] : ''}
onChange={e => setStart(e.target.value)}
/>
<label>End date</label>
<Input
type="date"
value={end ? end.split('T')[0] : ''}
onChange={e => setEnd(e.target.value)}
/>
</>
)}
<DialogFooter>
<Button onClick={handleSave}>{editingId ? 'Update' : 'Save'}</Button>
</DialogFooter>

View File

@@ -1,6 +1,25 @@
import ICAL from "ical.js";
import type { CalendarEvent } from "@/lib/types";
function valToString(val: unknown): string | undefined {
if (!val) return undefined;
if (typeof val === "string") return val;
if ((val as any).toString) return (val as any).toString();
return undefined;
}
function valToISOString(val: unknown): string | undefined {
if (!val) return undefined;
if (typeof val === "string") {
const d = new Date(val);
return isNaN(d.getTime()) ? undefined : d.toISOString();
}
if ((val as any).toJSDate) {
return (val as any).toJSDate().toISOString();
}
return undefined;
}
export function parseICS(icsString: string): CalendarEvent[] {
const jcalData = ICAL.parse(icsString);
const comp = new ICAL.Component(jcalData);
@@ -8,14 +27,19 @@ export function parseICS(icsString: string): CalendarEvent[] {
return vevents.map((v) => {
const ev = new ICAL.Event(v);
const isAllDay = ev.startDate.isDate;
return {
id: ev.uid || crypto.randomUUID(),
title: ev.summary || "Untitled Event",
start: ev.startDate.toJSDate().toISOString().split("T")[0],
end: ev.endDate
? ev.endDate.toJSDate().toISOString().split("T")[0]
: undefined,
description: ev.description || "",
location: ev.location || "",
url: valToString(v.getFirstPropertyValue("url")),
start: ev.startDate.toJSDate().toISOString(),
end: ev.endDate ? ev.endDate.toJSDate().toISOString() : undefined,
allDay: isAllDay,
createdAt: valToISOString(v.getFirstPropertyValue("dtstamp")),
lastModified: valToISOString(v.getFirstPropertyValue("last-modified")),
};
});
}
@@ -23,19 +47,52 @@ export function parseICS(icsString: string): CalendarEvent[] {
export function generateICS(events: CalendarEvent[]): string {
const comp = new ICAL.Component(["vcalendar", [], []]);
comp.addPropertyWithValue("version", "2.0");
comp.addPropertyWithValue("prodid", "-//YourAppName//EN");
comp.addPropertyWithValue("prodid", "-//iCalPWA//EN");
events.forEach((ev) => {
const vevent = new ICAL.Component("vevent");
vevent.addPropertyWithValue("uid", ev.id);
vevent.addPropertyWithValue("summary", ev.title);
vevent.addPropertyWithValue("dtstart", ICAL.Time.fromDateString(ev.start));
if (ev.end) {
vevent.addPropertyWithValue("dtend", ICAL.Time.fromDateString(ev.end));
}
if (ev.description) {
if (ev.description)
vevent.addPropertyWithValue("description", ev.description);
if (ev.location) vevent.addPropertyWithValue("location", ev.location);
if (ev.url) vevent.addPropertyWithValue("url", ev.url);
if (ev.allDay) {
vevent.addPropertyWithValue(
"dtstart",
ICAL.Time.fromDateString(ev.start.split("T")[0]),
);
if (ev.end) {
vevent.addPropertyWithValue(
"dtend",
ICAL.Time.fromDateString(ev.end.split("T")[0]),
);
}
} else {
vevent.addPropertyWithValue(
"dtstart",
ICAL.Time.fromJSDate(new Date(ev.start)),
);
if (ev.end) {
vevent.addPropertyWithValue(
"dtend",
ICAL.Time.fromJSDate(new Date(ev.end)),
);
}
}
vevent.addPropertyWithValue(
"dtstamp",
ICAL.Time.fromJSDate(ev.createdAt ? new Date(ev.createdAt) : new Date()),
);
if (ev.lastModified) {
vevent.addPropertyWithValue(
"last-modified",
ICAL.Time.fromJSDate(new Date(ev.lastModified)),
);
}
comp.addSubcomponent(vevent);
});

View File

@@ -1,7 +1,12 @@
export type CalendarEvent = {
id: string;
id: string; // UID
title: string;
start: string; // ISO date string (YYYY-MM-DD)
end?: string;
description?: string;
location?: string;
url?: string;
start: string; // ISO datetime
end?: string;
allDay?: boolean;
createdAt?: string;
lastModified?: string;
};