mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
Add integrated Google Calendar dashboard
Add a dashboard for managing Google Calendar events and tasks, including create, edit, delete, status updates, search, and integration error notices.
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
'use client';
|
||||
|
||||
import { AlertTriangle, ExternalLink } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface ApiNoticeBannerProps {
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
export default function ApiNoticeBanner({ error }: ApiNoticeBannerProps) {
|
||||
if (!error) return null;
|
||||
|
||||
const isApiDisabledError =
|
||||
error.includes('belum diaktifkan') ||
|
||||
error.includes('Google Calendar API has not been used') ||
|
||||
error.includes('disabled');
|
||||
|
||||
const isOAuthMismatchError =
|
||||
error.includes('unauthorized_client') || error.includes('invalid_grant');
|
||||
|
||||
const enableUrl =
|
||||
'https://console.developers.google.com/apis/api/calendar-json.googleapis.com/overview?project=141775000325';
|
||||
const playgroundUrl = 'https://developers.google.com/oauthplayground/';
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-xl border border-amber-300 bg-amber-50/80 p-4 text-amber-950 dark:border-amber-800/60 dark:bg-amber-950/30 dark:text-amber-200 shadow-xs"
|
||||
>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertTriangle className="size-5 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1">
|
||||
<h4 className="text-sm font-semibold tracking-tight">
|
||||
{isApiDisabledError
|
||||
? 'Google Calendar API Belum Diaktifkan di Project Cloud'
|
||||
: isOAuthMismatchError
|
||||
? 'Konfigurasi OAuth2 Refresh Token Perlu Diperbarui'
|
||||
: 'Pemberitahuan Sinkronisasi Google Calendar'}
|
||||
</h4>
|
||||
<p className="text-xs text-amber-900/90 dark:text-amber-300/90 leading-relaxed max-w-3xl">
|
||||
{error}
|
||||
</p>
|
||||
{isOAuthMismatchError && (
|
||||
<ol className="text-xs text-amber-800 dark:text-amber-300 list-decimal list-inside space-y-0.5 pt-1">
|
||||
<li>
|
||||
Pastikan <code className="font-mono">https://developers.google.com/oauthplayground</code> sudah ditambahkan ke <strong>Authorized redirect URIs</strong> pada OAuth 2.0 Client ID Anda di Google Cloud Console.
|
||||
</li>
|
||||
<li>
|
||||
Buka OAuth 2.0 Playground, klik ikon <strong>Gear (⚙️)</strong> di kanan atas, centang <strong>"Use your own OAuth credentials"</strong>, lalu isi <code className="font-mono">GOOGLE_CLIENT_ID</code> & <code className="font-mono">GOOGLE_CLIENT_SECRET</code> Anda.
|
||||
</li>
|
||||
<li>
|
||||
Pilih scope <code className="font-mono">https://www.googleapis.com/auth/calendar</code> > klik <strong>Authorize APIs</strong> > klik <strong>Exchange authorization code for tokens</strong> > salin <strong>Refresh token</strong> baru ke <code className="font-mono">.env.development</code>.
|
||||
</li>
|
||||
</ol>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isApiDisabledError && (
|
||||
<Button
|
||||
asChild
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="shrink-0 border-amber-400 bg-white hover:bg-amber-100 text-amber-900 dark:border-amber-700 dark:bg-amber-900/40 dark:text-amber-100 dark:hover:bg-amber-900/70"
|
||||
>
|
||||
<a href={enableUrl} target="_blank" rel="noopener noreferrer">
|
||||
<span>Aktifkan API Sekarang</span>
|
||||
<ExternalLink className="size-3.5 ml-1.5" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isOAuthMismatchError && (
|
||||
<Button
|
||||
asChild
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="shrink-0 border-amber-400 bg-white hover:bg-amber-100 text-amber-900 dark:border-amber-700 dark:bg-amber-900/40 dark:text-amber-100 dark:hover:bg-amber-900/70"
|
||||
>
|
||||
<a href={playgroundUrl} target="_blank" rel="noopener noreferrer">
|
||||
<span>Buka OAuth Playground</span>
|
||||
<ExternalLink className="size-3.5 ml-1.5" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
'use client';
|
||||
|
||||
import { Calendar as CalendarIcon, ExternalLink, RefreshCw, Plus, CheckSquare } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
interface CalendarHeaderProps {
|
||||
calendarId?: string;
|
||||
serviceAccountEmail?: string;
|
||||
onRefresh: () => void;
|
||||
onAddEvent: () => void;
|
||||
onAddTask: () => void;
|
||||
isRefreshing?: boolean;
|
||||
}
|
||||
|
||||
export default function CalendarHeader({
|
||||
calendarId,
|
||||
serviceAccountEmail,
|
||||
onRefresh,
|
||||
onAddEvent,
|
||||
onAddTask,
|
||||
isRefreshing = false,
|
||||
}: CalendarHeaderProps) {
|
||||
const googleCalendarWebUrl = calendarId
|
||||
? `https://calendar.google.com/calendar/u/0/r?cid=${encodeURIComponent(calendarId)}`
|
||||
: 'https://calendar.google.com';
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 pb-4 border-b border-zinc-200 dark:border-zinc-800">
|
||||
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
|
||||
{/* Title & Info */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="p-2 rounded-lg bg-zinc-100 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100">
|
||||
<CalendarIcon className="size-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100">
|
||||
Google Calendar & Task Testing
|
||||
</h1>
|
||||
<p className="text-xs md:text-sm text-zinc-500 dark:text-zinc-400">
|
||||
Integrasi Server-to-Server (Single System OAuth2 Refresh Token) • Tanpa OAuth Login Pengguna
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Badges Info */}
|
||||
<div className="flex flex-wrap items-center gap-2 pt-1 text-xs">
|
||||
<span className="text-zinc-500 font-medium">Koneksi Aktif:</span>
|
||||
{calendarId && (
|
||||
<Badge variant="outline" className="font-mono text-[11px] max-w-[280px] sm:max-w-none truncate">
|
||||
Cal: {calendarId}
|
||||
</Badge>
|
||||
)}
|
||||
{serviceAccountEmail && (
|
||||
<Badge variant="outline" className="font-mono text-[11px] max-w-[260px] sm:max-w-none truncate">
|
||||
Auth: {serviceAccountEmail}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onRefresh}
|
||||
disabled={isRefreshing}
|
||||
className="h-9 px-3"
|
||||
>
|
||||
<RefreshCw className={`size-3.5 mr-1.5 ${isRefreshing ? 'animate-spin' : ''}`} />
|
||||
<span>Muat Ulang</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
asChild
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9 px-3"
|
||||
>
|
||||
<a href={googleCalendarWebUrl} target="_blank" rel="noopener noreferrer">
|
||||
<span>Buka Google Calendar</span>
|
||||
<ExternalLink className="size-3.5 ml-1.5" />
|
||||
</a>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onAddTask}
|
||||
className="h-9 px-3 border-emerald-600 text-emerald-700 dark:text-emerald-400 dark:border-emerald-700 hover:bg-emerald-50 dark:hover:bg-emerald-950/40"
|
||||
>
|
||||
<CheckSquare className="size-3.5 mr-1.5" />
|
||||
<span>Tambah Task</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={onAddEvent}
|
||||
>
|
||||
<Plus className="size-3.5 mr-1.5" />
|
||||
<span>Tambah Event</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import { Calendar, CheckCircle2, Clock, ListTodo } from 'lucide-react';
|
||||
import { Card900 } from '@/components/ui/card';
|
||||
|
||||
interface CalendarStatsOverviewProps {
|
||||
totalEvents: number;
|
||||
totalTasks: number;
|
||||
completedTasks: number;
|
||||
pendingTasks: number;
|
||||
}
|
||||
|
||||
export default function CalendarStatsOverview({
|
||||
totalEvents,
|
||||
totalTasks,
|
||||
completedTasks,
|
||||
pendingTasks,
|
||||
}: CalendarStatsOverviewProps) {
|
||||
const cards = [
|
||||
{
|
||||
title: 'Total Event Kalender',
|
||||
value: totalEvents,
|
||||
icon: Calendar,
|
||||
desc: 'Agenda terjadwal di Google Calendar',
|
||||
iconColor: 'text-sky-600 dark:text-sky-400',
|
||||
bgColor: 'bg-sky-50 dark:bg-sky-950/40',
|
||||
},
|
||||
{
|
||||
title: 'Total Task',
|
||||
value: totalTasks,
|
||||
icon: ListTodo,
|
||||
desc: 'Item task berlabel [TASK]',
|
||||
iconColor: 'text-indigo-600 dark:text-indigo-400',
|
||||
bgColor: 'bg-indigo-50 dark:bg-indigo-950/40',
|
||||
},
|
||||
{
|
||||
title: 'Task Selesai',
|
||||
value: completedTasks,
|
||||
icon: CheckCircle2,
|
||||
desc: 'Status: completed / selesai',
|
||||
iconColor: 'text-emerald-600 dark:text-emerald-400',
|
||||
bgColor: 'bg-emerald-50 dark:bg-emerald-950/40',
|
||||
},
|
||||
{
|
||||
title: 'Task Tertunda',
|
||||
value: pendingTasks,
|
||||
icon: Clock,
|
||||
desc: 'Status: needsAction / menunggu',
|
||||
iconColor: 'text-amber-600 dark:text-amber-400',
|
||||
bgColor: 'bg-amber-50 dark:bg-amber-950/80',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
|
||||
{cards.map((card, idx) => {
|
||||
const Icon = card.icon;
|
||||
return (
|
||||
<Card900
|
||||
key={idx}
|
||||
className="p-4 rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 gap-2 shadow-xs"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">
|
||||
{card.title}
|
||||
</span>
|
||||
<div className={`p-1.5 rounded-lg ${card.bgColor} ${card.iconColor}`}>
|
||||
<Icon className="size-4" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-2xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100">
|
||||
{card.value}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-zinc-400 dark:text-zinc-500 truncate">
|
||||
{card.desc}
|
||||
</p>
|
||||
</Card900>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogCancel,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { deleteCalendarEvent } from '@/lib/google-calendar/events.actions';
|
||||
import { deleteCalendarTask } from '@/lib/google-calendar/tasks.actions';
|
||||
import { toast } from 'sonner';
|
||||
import { Loader2, AlertCircle } from 'lucide-react';
|
||||
|
||||
interface DeleteConfirmDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
item: {
|
||||
id: string;
|
||||
title: string;
|
||||
type: 'event' | 'task';
|
||||
} | null;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function DeleteConfirmDialog({ open, onOpenChange, item, onSuccess }: DeleteConfirmDialogProps) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
if (!item) return null;
|
||||
|
||||
const handleConfirmDelete = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
const res = item.type === 'event' ? await deleteCalendarEvent(item.id) : await deleteCalendarTask(item.id);
|
||||
|
||||
if (res.success) {
|
||||
toast.success(`${item.type === 'event' ? 'Event' : 'Task'} berhasil dihapus dari Google Calendar.`);
|
||||
onOpenChange(false);
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(res.error || 'Gagal menghapus data.');
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Terjadi kesalahan sistem.';
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent className="bg-white dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
|
||||
<AlertDialogHeader>
|
||||
<div className="flex items-center gap-2.5 text-rose-600 dark:text-rose-500 mb-1">
|
||||
<AlertCircle className="size-5" />
|
||||
<AlertDialogTitle className="text-base font-semibold">
|
||||
Hapus {item.type === 'event' ? 'Event' : 'Task'}?
|
||||
</AlertDialogTitle>
|
||||
</div>
|
||||
<AlertDialogDescription className="text-xs text-zinc-600 dark:text-zinc-400 leading-relaxed">
|
||||
Apakah Anda yakin ingin menghapus{' '}
|
||||
<strong className="text-zinc-900 dark:text-zinc-100 font-semibold">
|
||||
"{item.title}"
|
||||
</strong>
|
||||
? Agenda ini akan dihapus secara permanen dari akun Google Calendar resmi Anda.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
|
||||
<AlertDialogFooter className="mt-4 gap-2">
|
||||
<AlertDialogCancel disabled={loading} className="text-xs h-9 border-zinc-200 dark:border-zinc-800">
|
||||
Batal
|
||||
</AlertDialogCancel>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
onClick={handleConfirmDelete}
|
||||
disabled={loading}
|
||||
className="h-9 px-3 text-xs font-medium"
|
||||
>
|
||||
{loading && <Loader2 className="size-3.5 mr-1.5 animate-spin" />}
|
||||
Hapus Permanen
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
'use client';
|
||||
|
||||
import React, { useRef, useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Bold,
|
||||
Italic,
|
||||
Underline,
|
||||
ListOrdered,
|
||||
List,
|
||||
Link2,
|
||||
RemoveFormatting,
|
||||
AlignLeft,
|
||||
Globe,
|
||||
Pencil,
|
||||
X,
|
||||
ExternalLink,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface DescriptionRichEditorProps {
|
||||
value: string;
|
||||
onChange: (html: string) => void;
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
interface ActiveFormats {
|
||||
bold: boolean;
|
||||
italic: boolean;
|
||||
underline: boolean;
|
||||
insertOrderedList: boolean;
|
||||
insertUnorderedList: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic HTML sanitizer allowing safe Google Calendar formatting tags:
|
||||
* b, strong, i, em, u, ul, ol, li, br, p, div, span, a (href, target, rel)
|
||||
*/
|
||||
export function sanitizeCalendarHtml(dirtyHtml?: string): string {
|
||||
if (!dirtyHtml) return '';
|
||||
|
||||
return dirtyHtml
|
||||
.replace(/<(script|style|iframe|object|embed|form)[^>]*>[\s\S]*?<\/\1>/gi, '')
|
||||
.replace(/\son\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, '')
|
||||
.replace(/href\s*=\s*["']?\s*javascript:[^"'\s>]*/gi, 'href="#"');
|
||||
}
|
||||
|
||||
export default function DescriptionRichEditor({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = 'Add description',
|
||||
disabled = false,
|
||||
}: DescriptionRichEditorProps) {
|
||||
const editorRef = useRef<HTMLDivElement>(null);
|
||||
const isInternalChange = useRef(false);
|
||||
const savedRangeRef = useRef<Range | null>(null);
|
||||
|
||||
const [formats, setFormats] = useState<ActiveFormats>({
|
||||
bold: false,
|
||||
italic: false,
|
||||
underline: false,
|
||||
insertOrderedList: false,
|
||||
insertUnorderedList: false,
|
||||
});
|
||||
|
||||
// Google Calendar "Edit link" modal state
|
||||
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||
const [linkText, setLinkText] = useState('');
|
||||
const [linkUrl, setLinkUrl] = useState('');
|
||||
const editingAnchorRef = useRef<HTMLAnchorElement | null>(null);
|
||||
|
||||
// Active link under cursor (for Google Calendar's bottom floating link bar [✏️ | ✕])
|
||||
const activeAnchorRef = useRef<HTMLAnchorElement | null>(null);
|
||||
const [hasActiveAnchor, setHasActiveAnchor] = useState(false);
|
||||
const [activeAnchorHref, setActiveAnchorHref] = useState('');
|
||||
|
||||
// Sync external value into contentEditable only when not actively typing inside it
|
||||
useEffect(() => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
if (!isInternalChange.current && el.innerHTML !== value) {
|
||||
el.innerHTML = sanitizeCalendarHtml(value);
|
||||
}
|
||||
isInternalChange.current = false;
|
||||
}, [value]);
|
||||
|
||||
const findParentAnchor = useCallback((node: Node | null): HTMLAnchorElement | null => {
|
||||
const el = editorRef.current;
|
||||
if (!el || !node) return null;
|
||||
let curr: Node | null = node;
|
||||
while (curr && curr !== el) {
|
||||
if (curr.nodeName === 'A') {
|
||||
return curr as HTMLAnchorElement;
|
||||
}
|
||||
curr = curr.parentNode;
|
||||
}
|
||||
return null;
|
||||
}, []);
|
||||
|
||||
const checkActiveFormats = useCallback(() => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
try {
|
||||
const sel = window.getSelection();
|
||||
if (sel && sel.rangeCount > 0 && el.contains(sel.anchorNode)) {
|
||||
savedRangeRef.current = sel.getRangeAt(0).cloneRange();
|
||||
const anchor = findParentAnchor(sel.anchorNode);
|
||||
activeAnchorRef.current = anchor;
|
||||
setHasActiveAnchor(Boolean(anchor));
|
||||
setActiveAnchorHref(anchor?.getAttribute('href') || '');
|
||||
}
|
||||
|
||||
setFormats({
|
||||
bold: document.queryCommandState('bold'),
|
||||
italic: document.queryCommandState('italic'),
|
||||
underline: document.queryCommandState('underline'),
|
||||
insertOrderedList: document.queryCommandState('insertOrderedList'),
|
||||
insertUnorderedList: document.queryCommandState('insertUnorderedList'),
|
||||
});
|
||||
} catch {
|
||||
// Ignore if selection state is unavailable
|
||||
}
|
||||
}, [findParentAnchor]);
|
||||
|
||||
const emitChange = useCallback(() => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
isInternalChange.current = true;
|
||||
const rawHtml = el.innerHTML;
|
||||
const textOnly = el.textContent?.trim() || '';
|
||||
const hasList = /<(ul|ol|li)\b/i.test(rawHtml);
|
||||
|
||||
if (!textOnly && !hasList) {
|
||||
onChange('');
|
||||
} else {
|
||||
onChange(sanitizeCalendarHtml(rawHtml));
|
||||
}
|
||||
checkActiveFormats();
|
||||
}, [onChange, checkActiveFormats]);
|
||||
|
||||
const ensureSelectionInsideEditor = () => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
el.focus();
|
||||
const sel = window.getSelection();
|
||||
if (!sel) return;
|
||||
|
||||
if (sel.rangeCount > 0 && el.contains(sel.anchorNode)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (savedRangeRef.current && el.contains(savedRangeRef.current.commonAncestorContainer)) {
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(savedRangeRef.current);
|
||||
return;
|
||||
}
|
||||
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
};
|
||||
|
||||
const executeCommand = (command: string, arg?: string) => {
|
||||
if (disabled) return;
|
||||
ensureSelectionInsideEditor();
|
||||
document.execCommand(command, false, arg);
|
||||
emitChange();
|
||||
};
|
||||
|
||||
const handleClearFormatting = () => {
|
||||
if (disabled) return;
|
||||
ensureSelectionInsideEditor();
|
||||
document.execCommand('removeFormat', false);
|
||||
document.execCommand('unlink', false);
|
||||
emitChange();
|
||||
};
|
||||
|
||||
const handleOpenLinkDialog = (useActiveAnchor = false) => {
|
||||
if (disabled) return;
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const sel = window.getSelection();
|
||||
if (sel && sel.rangeCount > 0 && el.contains(sel.anchorNode)) {
|
||||
savedRangeRef.current = sel.getRangeAt(0).cloneRange();
|
||||
}
|
||||
|
||||
const targetAnchor = useActiveAnchor ? activeAnchorRef.current : activeAnchorRef.current;
|
||||
if (targetAnchor) {
|
||||
editingAnchorRef.current = targetAnchor;
|
||||
setLinkText(targetAnchor.textContent || '');
|
||||
setLinkUrl(targetAnchor.getAttribute('href') || '');
|
||||
} else {
|
||||
editingAnchorRef.current = null;
|
||||
const selectedStr =
|
||||
savedRangeRef.current && el.contains(savedRangeRef.current.commonAncestorContainer)
|
||||
? savedRangeRef.current.toString()
|
||||
: '';
|
||||
setLinkText(selectedStr);
|
||||
setLinkUrl('');
|
||||
}
|
||||
|
||||
setLinkDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleApplyLink = () => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const rawUrl = linkUrl.trim();
|
||||
if (!rawUrl) {
|
||||
setLinkDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const finalUrl = /^https?:\/\/|^mailto:|^tel:/i.test(rawUrl)
|
||||
? rawUrl
|
||||
: `https://${rawUrl}`;
|
||||
const displayText = linkText.trim() || rawUrl;
|
||||
|
||||
const currentEditingAnchor = editingAnchorRef.current;
|
||||
if (currentEditingAnchor && el.contains(currentEditingAnchor)) {
|
||||
currentEditingAnchor.setAttribute('href', finalUrl);
|
||||
currentEditingAnchor.setAttribute('target', '_blank');
|
||||
currentEditingAnchor.setAttribute('rel', 'noopener noreferrer');
|
||||
currentEditingAnchor.textContent = displayText;
|
||||
} else {
|
||||
el.focus();
|
||||
const sel = window.getSelection();
|
||||
if (sel) {
|
||||
sel.removeAllRanges();
|
||||
if (
|
||||
savedRangeRef.current &&
|
||||
el.contains(savedRangeRef.current.commonAncestorContainer)
|
||||
) {
|
||||
sel.addRange(savedRangeRef.current);
|
||||
} else {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
sel.addRange(range);
|
||||
}
|
||||
|
||||
const range = sel.getRangeAt(0);
|
||||
range.deleteContents();
|
||||
|
||||
const anchor = document.createElement('a');
|
||||
anchor.setAttribute('href', finalUrl);
|
||||
anchor.setAttribute('target', '_blank');
|
||||
anchor.setAttribute('rel', 'noopener noreferrer');
|
||||
anchor.textContent = displayText;
|
||||
|
||||
range.insertNode(anchor);
|
||||
|
||||
// Place cursor right after the inserted link
|
||||
range.setStartAfter(anchor);
|
||||
range.setEndAfter(anchor);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
savedRangeRef.current = range.cloneRange();
|
||||
}
|
||||
}
|
||||
|
||||
setLinkDialogOpen(false);
|
||||
editingAnchorRef.current = null;
|
||||
emitChange();
|
||||
};
|
||||
|
||||
const handleUnlinkActive = () => {
|
||||
const el = editorRef.current;
|
||||
const targetAnchor = activeAnchorRef.current;
|
||||
if (!el || !targetAnchor) return;
|
||||
|
||||
const textNode = document.createTextNode(targetAnchor.textContent || '');
|
||||
targetAnchor.parentNode?.replaceChild(textNode, targetAnchor);
|
||||
activeAnchorRef.current = null;
|
||||
setHasActiveAnchor(false);
|
||||
setActiveAnchorHref('');
|
||||
emitChange();
|
||||
};
|
||||
|
||||
const isEmpty = !value || value === '<br>' || value.trim() === '';
|
||||
|
||||
const toolbarBtnClass = (active: boolean) =>
|
||||
`size-8 rounded-full flex items-center justify-center transition-colors ${
|
||||
active
|
||||
? 'bg-zinc-200/90 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-50'
|
||||
: 'text-zinc-600 dark:text-zinc-300 hover:bg-zinc-200/50 dark:hover:bg-zinc-800 hover:text-zinc-900 dark:hover:text-zinc-100'
|
||||
} disabled:opacity-40 disabled:pointer-events-none`;
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
{/* Scoped CSS ensuring bullets, numbers, and blue links ALWAYS render inside the editor and EventList */}
|
||||
<style>{`
|
||||
.gcal-rich-content ul {
|
||||
list-style-type: disc !important;
|
||||
padding-left: 1.75rem !important;
|
||||
margin: 0.35rem 0 !important;
|
||||
}
|
||||
.gcal-rich-content ol {
|
||||
list-style-type: decimal !important;
|
||||
padding-left: 1.75rem !important;
|
||||
margin: 0.35rem 0 !important;
|
||||
}
|
||||
.gcal-rich-content li {
|
||||
display: list-item !important;
|
||||
margin: 0.15rem 0 !important;
|
||||
}
|
||||
.gcal-rich-content a,
|
||||
.gcal-rich-content a * {
|
||||
color: #1a73e8 !important;
|
||||
text-decoration: underline !important;
|
||||
text-underline-offset: 2px !important;
|
||||
cursor: pointer !important;
|
||||
}
|
||||
.dark .gcal-rich-content a,
|
||||
.dark .gcal-rich-content a * {
|
||||
color: #8ab4f8 !important;
|
||||
}
|
||||
`}</style>
|
||||
|
||||
<div className="rounded-lg border border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/80 overflow-hidden focus-within:border-zinc-400 dark:focus-within:border-zinc-600 transition-colors">
|
||||
{/* Google Calendar Style Toolbar */}
|
||||
<div className="flex flex-wrap items-center gap-0.5 px-2.5 py-1.5 border-b border-zinc-200/80 dark:border-zinc-800 bg-zinc-100/70 dark:bg-zinc-900">
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('bold');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Bold (Ctrl+B)"
|
||||
className={toolbarBtnClass(formats.bold)}
|
||||
>
|
||||
<Bold className="size-4 stroke-[2.5]" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('italic');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Italic (Ctrl+I)"
|
||||
className={toolbarBtnClass(formats.italic)}
|
||||
>
|
||||
<Italic className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('underline');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Underline (Ctrl+U)"
|
||||
className={toolbarBtnClass(formats.underline)}
|
||||
>
|
||||
<Underline className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<div className="h-5 w-px bg-zinc-300 dark:bg-zinc-700 mx-1.5" />
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('insertOrderedList');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Numbered list"
|
||||
className={toolbarBtnClass(formats.insertOrderedList)}
|
||||
>
|
||||
<ListOrdered className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('insertUnorderedList');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Bulleted list"
|
||||
className={toolbarBtnClass(formats.insertUnorderedList)}
|
||||
>
|
||||
<List className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<div className="h-5 w-px bg-zinc-300 dark:bg-zinc-700 mx-1.5" />
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleOpenLinkDialog(false);
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Insert link"
|
||||
className={toolbarBtnClass(linkDialogOpen || hasActiveAnchor)}
|
||||
>
|
||||
<Link2 className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleClearFormatting();
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Clear formatting"
|
||||
className={toolbarBtnClass(false)}
|
||||
>
|
||||
<RemoveFormatting className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Editable Content Area */}
|
||||
<div className="relative min-h-[120px] max-h-[240px] overflow-y-auto">
|
||||
{isEmpty && (
|
||||
<div className="pointer-events-none absolute top-3 left-3.5 text-xs sm:text-sm text-zinc-400 dark:text-zinc-500 select-none">
|
||||
{placeholder}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
ref={editorRef}
|
||||
contentEditable={!disabled}
|
||||
suppressContentEditableWarning
|
||||
onInput={emitChange}
|
||||
onKeyUp={checkActiveFormats}
|
||||
onMouseUp={checkActiveFormats}
|
||||
onBlur={emitChange}
|
||||
className="gcal-rich-content min-h-[120px] px-3.5 py-3 text-xs sm:text-sm text-zinc-900 dark:text-zinc-100 outline-none leading-relaxed break-words"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Google Calendar Floating Link Action Pill (when cursor is inside a link) */}
|
||||
{hasActiveAnchor && !linkDialogOpen && (
|
||||
<div className="mt-1.5 inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-zinc-900 text-zinc-100 dark:bg-zinc-800 dark:text-zinc-100 shadow-md border border-zinc-700 text-xs">
|
||||
<a
|
||||
href={activeAnchorHref}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sky-400 hover:underline truncate max-w-[200px] flex items-center gap-1"
|
||||
title={activeAnchorHref}
|
||||
>
|
||||
<span className="truncate">{activeAnchorHref}</span>
|
||||
<ExternalLink className="size-3 shrink-0" />
|
||||
</a>
|
||||
<div className="h-3.5 w-px bg-zinc-700" />
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleOpenLinkDialog(true);
|
||||
}}
|
||||
className="p-1 rounded hover:bg-zinc-700 text-zinc-300 hover:text-white transition-colors"
|
||||
title="Edit link"
|
||||
>
|
||||
<Pencil className="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleUnlinkActive();
|
||||
}}
|
||||
className="p-1 rounded hover:bg-zinc-700 text-zinc-300 hover:text-white transition-colors"
|
||||
title="Remove link"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Google Calendar "Edit link" Modal Overlay */}
|
||||
{linkDialogOpen && (
|
||||
<div className="mt-2 p-4 rounded-2xl border border-zinc-200 dark:border-zinc-700 bg-white dark:bg-zinc-900 shadow-lg space-y-3.5">
|
||||
<h4 className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
|
||||
Edit link
|
||||
</h4>
|
||||
|
||||
<div className="space-y-2.5">
|
||||
{/* Text to display */}
|
||||
<div className="flex items-center gap-3">
|
||||
<AlignLeft className="size-4 text-zinc-400 shrink-0" />
|
||||
<input
|
||||
type="text"
|
||||
value={linkText}
|
||||
onChange={(e) => setLinkText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleApplyLink();
|
||||
} else if (e.key === 'Escape') {
|
||||
setLinkDialogOpen(false);
|
||||
}
|
||||
}}
|
||||
placeholder="Text to display"
|
||||
className="flex-1 h-9 px-3 rounded-md text-xs sm:text-sm bg-zinc-100 dark:bg-zinc-800 border-b-2 border-transparent focus:border-sky-500 text-zinc-900 dark:text-zinc-100 outline-none transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Link to url address */}
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="size-4 text-zinc-400 shrink-0" />
|
||||
<input
|
||||
type="text"
|
||||
value={linkUrl}
|
||||
onChange={(e) => setLinkUrl(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleApplyLink();
|
||||
} else if (e.key === 'Escape') {
|
||||
setLinkDialogOpen(false);
|
||||
}
|
||||
}}
|
||||
placeholder="Link to url address"
|
||||
autoFocus
|
||||
className="flex-1 h-9 px-3 rounded-md text-xs sm:text-sm bg-zinc-100 dark:bg-zinc-800 border-b-2 border-sky-500 text-zinc-900 dark:text-zinc-100 outline-none transition-colors"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-2 pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLinkDialogOpen(false)}
|
||||
className="h-8 px-4 rounded-full text-xs font-medium text-sky-600 dark:text-sky-400 hover:bg-sky-50 dark:hover:bg-sky-950/50 transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!linkUrl.trim()}
|
||||
onClick={handleApplyLink}
|
||||
className="h-8 px-5 rounded-full text-xs font-medium bg-sky-600 hover:bg-sky-500 text-white disabled:bg-zinc-200 disabled:text-zinc-400 dark:disabled:bg-zinc-800 dark:disabled:text-zinc-500 transition-colors"
|
||||
>
|
||||
OK
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import DescriptionRichEditor from './DescriptionRichEditor';
|
||||
import { CalendarEventItem } from '@/lib/google-calendar/types';
|
||||
import { GOOGLE_EVENT_COLORS, getEventColorInfo } from '@/lib/google-calendar/constants';
|
||||
import { createCalendarEvent, updateCalendarEvent } from '@/lib/google-calendar/events.actions';
|
||||
import { toast } from 'sonner';
|
||||
import { Loader2, Plus, X, Video, Users, Palette, Check } from 'lucide-react';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface EventFormModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
event?: CalendarEventItem | null;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
interface FormInnerProps {
|
||||
event?: CalendarEventItem | null;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
function EventFormInner({ event, onClose, onSuccess }: FormInnerProps) {
|
||||
const isEdit = Boolean(event);
|
||||
|
||||
const defaultStart = event
|
||||
? event.isAllDay
|
||||
? dayjs(event.start).format('YYYY-MM-DD')
|
||||
: dayjs(event.start).format('YYYY-MM-DDTHH:mm')
|
||||
: dayjs().add(1, 'hour').minute(0).second(0).format('YYYY-MM-DDTHH:mm');
|
||||
|
||||
const defaultEnd = event
|
||||
? event.isAllDay
|
||||
? dayjs(event.end || event.start).format('YYYY-MM-DD')
|
||||
: dayjs(event.end).format('YYYY-MM-DDTHH:mm')
|
||||
: dayjs().add(2, 'hour').minute(0).second(0).format('YYYY-MM-DDTHH:mm');
|
||||
|
||||
const [summary, setSummary] = useState(event?.summary || '');
|
||||
const [description, setDescription] = useState(event?.description || '');
|
||||
const [location, setLocation] = useState(event?.location || '');
|
||||
const [isAllDay, setIsAllDay] = useState(event?.isAllDay || false);
|
||||
const [startDateTime, setStartDateTime] = useState(defaultStart);
|
||||
const [endDateTime, setEndDateTime] = useState(defaultEnd);
|
||||
|
||||
// New fields: colorId, attendees, Google Meet
|
||||
const [colorId, setColorId] = useState<string>(event?.colorId || '');
|
||||
const [attendees, setAttendees] = useState<string[]>(event?.attendees || []);
|
||||
const [guestInput, setGuestInput] = useState('');
|
||||
const [generateMeet, setGenerateMeet] = useState(false);
|
||||
const [manualMeetLink, setManualMeetLink] = useState(event?.hangoutLink || '');
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const selectedColorInfo = getEventColorInfo(colorId);
|
||||
|
||||
const handleAddGuest = () => {
|
||||
const raw = guestInput.trim().toLowerCase().replace(/,$/, '');
|
||||
if (!raw) return;
|
||||
|
||||
if (!EMAIL_REGEX.test(raw)) {
|
||||
toast.error(`Format email "${raw}" tidak valid.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (attendees.includes(raw)) {
|
||||
toast.info(`Email "${raw}" sudah ada di daftar tamu.`);
|
||||
setGuestInput('');
|
||||
return;
|
||||
}
|
||||
|
||||
setAttendees((prev) => [...prev, raw]);
|
||||
setGuestInput('');
|
||||
};
|
||||
|
||||
const handleGuestKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter' || e.key === ',') {
|
||||
e.preventDefault();
|
||||
handleAddGuest();
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveGuest = (emailToRemove: string) => {
|
||||
setAttendees((prev) => prev.filter((email) => email !== emailToRemove));
|
||||
};
|
||||
|
||||
const handleStartChange = (val: string) => {
|
||||
setStartDateTime(val);
|
||||
if (!val) return;
|
||||
|
||||
if (isAllDay) {
|
||||
if (endDateTime && dayjs(endDateTime).isBefore(dayjs(val), 'day')) {
|
||||
setEndDateTime(dayjs(val).format('YYYY-MM-DD'));
|
||||
}
|
||||
} else {
|
||||
if (endDateTime && !dayjs(endDateTime).isAfter(dayjs(val))) {
|
||||
setEndDateTime(dayjs(val).add(1, 'hour').format('YYYY-MM-DDTHH:mm'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!summary.trim()) {
|
||||
toast.error('Judul event wajib diisi!');
|
||||
return;
|
||||
}
|
||||
if (!startDateTime || !endDateTime) {
|
||||
toast.error('Waktu mulai dan selesai wajib diisi!');
|
||||
return;
|
||||
}
|
||||
|
||||
// If user typed a valid email in guestInput without clicking "Tambah", include it
|
||||
const finalAttendees = [...attendees];
|
||||
const pendingGuest = guestInput.trim().toLowerCase();
|
||||
if (pendingGuest) {
|
||||
if (!EMAIL_REGEX.test(pendingGuest)) {
|
||||
toast.error(`Format email tamu "${pendingGuest}" tidak valid.`);
|
||||
return;
|
||||
}
|
||||
if (!finalAttendees.includes(pendingGuest)) {
|
||||
finalAttendees.push(pendingGuest);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
const payload = {
|
||||
summary,
|
||||
description,
|
||||
location,
|
||||
startDateTime,
|
||||
endDateTime,
|
||||
isAllDay,
|
||||
colorId: colorId || undefined,
|
||||
attendees: finalAttendees,
|
||||
generateMeet,
|
||||
manualMeetLink: manualMeetLink.trim() || undefined,
|
||||
};
|
||||
|
||||
const res = isEdit && event ? await updateCalendarEvent(event.id, payload) : await createCalendarEvent(payload);
|
||||
|
||||
if (res.success) {
|
||||
toast.success(isEdit ? 'Event berhasil diperbarui di Google Calendar!' : 'Event berhasil ditambahkan ke Google Calendar!');
|
||||
if (res.warning) {
|
||||
toast.warning(res.warning, { duration: 6000 });
|
||||
}
|
||||
onClose();
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(res.error || 'Gagal menyimpan event.', { duration: 5000 });
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Terjadi kesalahan tidak terduga.';
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col">
|
||||
<DialogHeader className="p-6 pb-4 border-b border-zinc-100 dark:border-zinc-800">
|
||||
<DialogTitle className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
{isEdit ? 'Edit Event Google Calendar' : 'Tambah Event Baru'}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400">
|
||||
Perubahan akan langsung disinkronkan ke kalender Google secara real-time.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
|
||||
{/* Summary */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="event-summary" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Judul Event <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="event-summary"
|
||||
placeholder="misal: Rapat Koordinasi Tim Project"
|
||||
value={summary}
|
||||
onChange={(e) => setSummary(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* All Day Toggle */}
|
||||
<div className="flex items-center justify-between p-3 rounded-lg bg-zinc-50 dark:bg-zinc-900/60 border border-zinc-200/80 dark:border-zinc-800">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="all-day-toggle" className="text-xs font-semibold text-zinc-800 dark:text-zinc-200 cursor-pointer">
|
||||
Acara Sepanjang Hari (All Day)
|
||||
</Label>
|
||||
<p className="text-[11px] text-zinc-500">
|
||||
Menggunakan format tanggal harian (YYYY-MM-DD) tanpa jam spesifik
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="all-day-toggle"
|
||||
checked={isAllDay}
|
||||
onCheckedChange={(checked) => {
|
||||
setIsAllDay(checked);
|
||||
if (checked) {
|
||||
const startDay = startDateTime.split('T')[0] || dayjs().format('YYYY-MM-DD');
|
||||
const endDay = endDateTime.split('T')[0] || startDay;
|
||||
setStartDateTime(startDay);
|
||||
setEndDateTime(dayjs(endDay).isBefore(dayjs(startDay), 'day') ? startDay : endDay);
|
||||
} else {
|
||||
const baseDay = startDateTime.split('T')[0] || dayjs().format('YYYY-MM-DD');
|
||||
const startFull = dayjs(`${baseDay}T09:00`).format('YYYY-MM-DDTHH:mm');
|
||||
const endFull = dayjs(`${baseDay}T10:00`).format('YYYY-MM-DDTHH:mm');
|
||||
setStartDateTime(startFull);
|
||||
setEndDateTime(endFull);
|
||||
}
|
||||
}}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Dates: Start & End */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="event-start" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
{isAllDay ? 'Tanggal Mulai' : 'Waktu Mulai'} <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="event-start"
|
||||
type={isAllDay ? 'date' : 'datetime-local'}
|
||||
value={startDateTime}
|
||||
onChange={(e) => handleStartChange(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
className="h-9 text-xs sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="event-end" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
{isAllDay ? 'Tanggal Selesai (Inklusif)' : 'Waktu Selesai'} <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="event-end"
|
||||
type={isAllDay ? 'date' : 'datetime-local'}
|
||||
value={endDateTime}
|
||||
min={startDateTime}
|
||||
onChange={(e) => setEndDateTime(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
className="h-9 text-xs sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Event Color Picker (colorId 1 - 11) */}
|
||||
<div className="space-y-2 p-3 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900/40">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 flex items-center gap-1.5">
|
||||
<Palette className="size-3.5 text-zinc-500" />
|
||||
<span>Warna Event (colorId)</span>
|
||||
</Label>
|
||||
<span className="text-[11px] font-medium text-zinc-500 dark:text-zinc-400">
|
||||
{selectedColorInfo
|
||||
? `${selectedColorInfo.id} - ${selectedColorInfo.name}`
|
||||
: 'Default Kalender'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 pt-1">
|
||||
{/* Default / No colorId */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setColorId('')}
|
||||
disabled={loading}
|
||||
title="Default Kalender"
|
||||
className={`h-6 px-2 rounded-full text-[11px] font-medium border transition-all flex items-center gap-1 ${colorId === ''
|
||||
? 'bg-zinc-900 text-white'
|
||||
: 'border-zinc-300 dark:border-zinc-700 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800'
|
||||
}`}
|
||||
>
|
||||
Default
|
||||
</button>
|
||||
|
||||
{GOOGLE_EVENT_COLORS.map((color) => {
|
||||
const isSelected = colorId === color.id;
|
||||
return (
|
||||
<button
|
||||
key={color.id}
|
||||
type="button"
|
||||
onClick={() => setColorId(color.id)}
|
||||
disabled={loading}
|
||||
title={`${color.id}: ${color.name}`}
|
||||
style={{ backgroundColor: color.hex }}
|
||||
className={`size-6 rounded-full flex items-center justify-center transition-transform ${isSelected
|
||||
? 'ring-2 ring-offset-2 ring-zinc-900 dark:ring-zinc-100 dark:ring-offset-zinc-950 scale-110'
|
||||
: 'opacity-85 hover:opacity-100 hover:scale-105'
|
||||
}`}
|
||||
>
|
||||
{isSelected && <Check className="size-3.5 text-white stroke-[3]" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Add Guest (attendees) */}
|
||||
<div className="space-y-2 p-3 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900/40">
|
||||
<Label htmlFor="event-guest-input" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 flex items-center gap-1.5">
|
||||
<Users className="size-3.5 text-zinc-500" />
|
||||
<span>Tambah Tamu / Peserta (Attendees)</span>
|
||||
</Label>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="event-guest-input"
|
||||
type="email"
|
||||
placeholder="Ketik email tamu lalu tekan Enter / Tambah..."
|
||||
value={guestInput}
|
||||
onChange={(e) => setGuestInput(e.target.value)}
|
||||
onKeyDown={handleGuestKeyDown}
|
||||
disabled={loading}
|
||||
className="h-8 text-xs flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleAddGuest}
|
||||
disabled={loading || !guestInput.trim()}
|
||||
className="h-8 px-2.5 text-xs shrink-0"
|
||||
>
|
||||
<Plus className="size-3.5 mr-1" />
|
||||
Tambah
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{attendees.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 pt-1">
|
||||
{attendees.map((email) => (
|
||||
<Badge
|
||||
key={email}
|
||||
variant="secondary"
|
||||
className="text-[11px] py-0.5 pl-2 pr-1 gap-1 font-normal bg-zinc-100 dark:bg-zinc-800 text-zinc-800 dark:text-zinc-200"
|
||||
>
|
||||
<span className="truncate max-w-[210px]">{email}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveGuest(email)}
|
||||
disabled={loading}
|
||||
className="p-0.5 rounded-full hover:bg-zinc-300 dark:hover:bg-zinc-700 text-zinc-500 hover:text-zinc-900 dark:hover:text-zinc-100"
|
||||
title={`Hapus ${email}`}
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Google Meet (conferenceData / hangoutLink) */}
|
||||
<div className="space-y-3 p-3 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900/40">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="meet-toggle" className="text-xs font-semibold text-zinc-800 dark:text-zinc-200 flex items-center gap-1.5 cursor-pointer">
|
||||
<Video className="size-3.5 text-sky-600 dark:text-sky-400" />
|
||||
<span>Generate Link Google Meet Otomatis</span>
|
||||
</Label>
|
||||
<p className="text-[11px] text-zinc-500">
|
||||
Mengirim <code className="text-[10px]">conferenceData.createRequest</code> (<code className="text-[10px]">conferenceDataVersion: 1</code>)
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="meet-toggle"
|
||||
checked={generateMeet}
|
||||
onCheckedChange={setGenerateMeet}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 pt-1 border-t border-zinc-100 dark:border-zinc-800/80">
|
||||
<Label htmlFor="manual-meet-link" className="text-[11px] font-medium text-zinc-600 dark:text-zinc-400">
|
||||
Link Google Meet Manual (Fallback jika kalender non-Workspace / Custom Meet URL)
|
||||
</Label>
|
||||
<Input
|
||||
id="manual-meet-link"
|
||||
type="url"
|
||||
placeholder="https://meet.google.com/xxx-xxxx-xxx (opsional)"
|
||||
value={manualMeetLink}
|
||||
onChange={(e) => setManualMeetLink(e.target.value)}
|
||||
disabled={loading}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Location */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="event-location" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Lokasi / Ruangan (Opsional)
|
||||
</Label>
|
||||
<Input
|
||||
id="event-location"
|
||||
placeholder="misal: Ruang Meeting Lantai 2"
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
disabled={loading}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Deskripsi / Catatan (Opsional)
|
||||
</Label>
|
||||
<DescriptionRichEditor
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
disabled={loading}
|
||||
placeholder="Add description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="p-4 bg-zinc-50 dark:bg-zinc-900/50 border-t border-zinc-100 dark:border-zinc-800 flex items-center justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
Batal
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading && <Loader2 className="size-3.5 mr-1.5 animate-spin" />}
|
||||
{isEdit ? 'Simpan Perubahan' : 'Buat Event'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EventFormModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
event,
|
||||
onSuccess,
|
||||
}: EventFormModalProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden bg-white dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
|
||||
{open && (
|
||||
<EventFormInner
|
||||
key={event?.id || 'new'}
|
||||
event={event}
|
||||
onClose={() => onOpenChange(false)}
|
||||
onSuccess={onSuccess}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { CalendarEventItem } from '@/lib/google-calendar/types';
|
||||
import { getEventColorInfo } from '@/lib/google-calendar/constants';
|
||||
import {
|
||||
Calendar,
|
||||
MapPin,
|
||||
Clock,
|
||||
Edit2,
|
||||
Trash2,
|
||||
ExternalLink,
|
||||
Search,
|
||||
Users,
|
||||
Video,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { sanitizeCalendarHtml } from './DescriptionRichEditor';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface EventListProps {
|
||||
events: CalendarEventItem[];
|
||||
onEdit: (event: CalendarEventItem) => void;
|
||||
onDelete: (event: CalendarEventItem) => void;
|
||||
onAddEvent: () => void;
|
||||
}
|
||||
|
||||
export default function EventList({
|
||||
events,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onAddEvent,
|
||||
}: EventListProps) {
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const filtered = events.filter((e) => {
|
||||
const q = search.toLowerCase();
|
||||
const guestMatch = e.attendees?.some((guest) => guest.toLowerCase().includes(q));
|
||||
return (
|
||||
e.summary.toLowerCase().includes(q) ||
|
||||
Boolean(e.description && e.description.toLowerCase().includes(q)) ||
|
||||
Boolean(e.location && e.location.toLowerCase().includes(q)) ||
|
||||
Boolean(guestMatch)
|
||||
);
|
||||
});
|
||||
|
||||
const formatDateRange = (startStr: string, endStr: string, isAllDay: boolean) => {
|
||||
if (!startStr) return '-';
|
||||
if (isAllDay) {
|
||||
const s = dayjs(startStr).format('DD MMM YYYY');
|
||||
const e =
|
||||
endStr && endStr !== startStr ? ` - ${dayjs(endStr).format('DD MMM YYYY')}` : '';
|
||||
return `${s}${e} (Sepanjang Hari)`;
|
||||
}
|
||||
const s = dayjs(startStr).format('DD MMM YYYY, HH:mm');
|
||||
const sameDay = dayjs(startStr).isSame(dayjs(endStr), 'day');
|
||||
const e = endStr
|
||||
? sameDay
|
||||
? dayjs(endStr).format('HH:mm')
|
||||
: dayjs(endStr).format('DD MMM YYYY, HH:mm')
|
||||
: '';
|
||||
return `${s} s/d ${e} WIB`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Search Bar */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-zinc-400 pointer-events-none" />
|
||||
<Input
|
||||
placeholder="Cari event (judul, lokasi, tamu, deskripsi)..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-9 h-9 text-xs sm:text-sm bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800"
|
||||
/>
|
||||
</div>
|
||||
<span className="text-xs text-zinc-500 font-medium">
|
||||
{filtered.length} dari {events.length} event
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* List Container */}
|
||||
{filtered.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-zinc-300 dark:border-zinc-800 p-8 text-center bg-zinc-50/50 dark:bg-zinc-900/30">
|
||||
<Calendar className="size-10 text-zinc-400 mx-auto mb-3 stroke-[1.5]" />
|
||||
<h3 className="text-sm font-semibold text-zinc-800 dark:text-zinc-200">
|
||||
{events.length === 0
|
||||
? 'Belum Ada Event di Google Calendar'
|
||||
: 'Tidak Ada Event yang Sesuai Pencarian'}
|
||||
</h3>
|
||||
<p className="text-xs text-zinc-500 max-w-sm mx-auto mt-1 mb-4">
|
||||
{events.length === 0
|
||||
? 'Tambahkan event baru untuk melakukan uji coba sinkronisasi ke Google Calendar web.'
|
||||
: 'Coba ubah kata kunci pencarian Anda.'}
|
||||
</p>
|
||||
{events.length === 0 && (
|
||||
<Button size="sm" onClick={onAddEvent} className="h-9">
|
||||
Tambah Event Pertama
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2.5">
|
||||
{filtered.map((item) => {
|
||||
const colorInfo = getEventColorInfo(item.colorId);
|
||||
const guestList = item.attendees || [];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
style={
|
||||
colorInfo
|
||||
? { borderLeftColor: colorInfo.hex, borderLeftWidth: '4px' }
|
||||
: undefined
|
||||
}
|
||||
className="group flex flex-col md:flex-row md:items-center justify-between p-4 rounded-xl border border-zinc-200 dark:border-zinc-800/80 bg-white dark:bg-zinc-900 hover:border-zinc-300 dark:hover:border-zinc-700 transition-colors shadow-xs gap-3"
|
||||
>
|
||||
{/* Event Info */}
|
||||
<div className="space-y-1.5 flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
className="size-2.5 rounded-full shrink-0"
|
||||
style={{ backgroundColor: colorInfo?.hex || '#039be5' }}
|
||||
title={
|
||||
colorInfo
|
||||
? `Warna: ${colorInfo.name} (ID ${colorInfo.id})`
|
||||
: 'Warna Default Kalender'
|
||||
}
|
||||
/>
|
||||
<h4 className="font-semibold text-sm sm:text-base text-zinc-900 dark:text-zinc-100 truncate">
|
||||
{item.summary}
|
||||
</h4>
|
||||
|
||||
{item.isAllDay && (
|
||||
<Badge variant="outline" className="text-[10px] py-0 px-1.5">
|
||||
All-Day
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{colorInfo && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] py-0 px-1.5 gap-1 font-normal border-zinc-200 dark:border-zinc-700"
|
||||
>
|
||||
<span
|
||||
className="size-1.5 rounded-full"
|
||||
style={{ backgroundColor: colorInfo.hex }}
|
||||
/>
|
||||
{colorInfo.name}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Date, Location & Guest Count */}
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-zinc-500 dark:text-zinc-400">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="size-3.5 text-zinc-400" />
|
||||
<span>{formatDateRange(item.start, item.end, item.isAllDay)}</span>
|
||||
</div>
|
||||
|
||||
{item.location && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<MapPin className="size-3.5 text-zinc-400" />
|
||||
<span className="truncate max-w-[220px]">{item.location}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{guestList.length > 0 && (
|
||||
<div
|
||||
className="flex items-center gap-1.5 text-zinc-600 dark:text-zinc-300"
|
||||
title={`Tamu: ${guestList.join(', ')}`}
|
||||
>
|
||||
<Users className="size-3.5 text-zinc-400" />
|
||||
<span>{guestList.length} Tamu</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Guest Email Badges */}
|
||||
{guestList.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1 pt-0.5">
|
||||
{guestList.slice(0, 3).map((email) => (
|
||||
<Badge
|
||||
key={email}
|
||||
variant="secondary"
|
||||
className="text-[10px] py-0 px-1.5 font-normal bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300"
|
||||
>
|
||||
{email}
|
||||
</Badge>
|
||||
))}
|
||||
{guestList.length > 3 && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] py-0 px-1.5 font-normal"
|
||||
title={guestList.slice(3).join(', ')}
|
||||
>
|
||||
+{guestList.length - 3} lainnya
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.description && (
|
||||
<div
|
||||
className="gcal-rich-content text-xs text-zinc-600 dark:text-zinc-300 pt-1 leading-relaxed break-words"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: sanitizeCalendarHtml(item.description),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex flex-wrap items-center gap-1.5 self-end md:self-center shrink-0 pt-2 md:pt-0 border-t md:border-t-0 border-zinc-100 dark:border-zinc-800/60 w-full md:w-auto justify-end">
|
||||
{item.hangoutLink && (
|
||||
<Button
|
||||
asChild
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 px-2.5 text-xs border-sky-200 bg-sky-50/60 text-sky-700 hover:bg-sky-100 dark:border-sky-900/60 dark:bg-sky-950/40 dark:text-sky-300 dark:hover:bg-sky-900/60"
|
||||
>
|
||||
<a href={item.hangoutLink} target="_blank" rel="noopener noreferrer">
|
||||
<Video className="size-3.5 mr-1.5" />
|
||||
<span>Google Meet</span>
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{item.htmlLink && (
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"
|
||||
title="Buka di Google Calendar"
|
||||
>
|
||||
<a href={item.htmlLink} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="size-3.5" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onEdit(item)}
|
||||
className="h-8 px-2.5 text-xs text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<Edit2 className="size-3 mr-1" />
|
||||
<span>Edit</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onDelete(item)}
|
||||
className="h-8 px-2.5 text-xs border-rose-200 text-rose-600 hover:bg-rose-50 dark:border-rose-900/60 dark:text-rose-400 dark:hover:bg-rose-950/40"
|
||||
>
|
||||
<Trash2 className="size-3 mr-1" />
|
||||
<span>Hapus</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useTransition } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
CalendarEventItem,
|
||||
CalendarTaskItem,
|
||||
CalendarSummaryStats,
|
||||
TaskStatus,
|
||||
} from '@/lib/google-calendar/types';
|
||||
import { getCalendarEvents } from '@/lib/google-calendar/events.actions';
|
||||
import {
|
||||
getCalendarTasks,
|
||||
toggleCalendarTaskStatus,
|
||||
getCalendarSummaryStats,
|
||||
} from '@/lib/google-calendar/tasks.actions';
|
||||
import CalendarHeader from './CalendarHeader';
|
||||
import CalendarStatsOverview from './CalendarStatsOverview';
|
||||
import ApiNoticeBanner from './ApiNoticeBanner';
|
||||
import EventList from './EventList';
|
||||
import TaskList from './TaskList';
|
||||
import EventFormModal from './EventFormModal';
|
||||
import TaskFormModal from './TaskFormModal';
|
||||
import DeleteConfirmDialog from './DeleteConfirmDialog';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import { Calendar, ListTodo } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
interface IntegratedCalendarClientProps {
|
||||
initialEvents: CalendarEventItem[];
|
||||
initialTasks: CalendarTaskItem[];
|
||||
initialStats: CalendarSummaryStats;
|
||||
initialError?: string | null;
|
||||
}
|
||||
|
||||
export default function IntegratedCalendarClient({
|
||||
initialEvents,
|
||||
initialTasks,
|
||||
initialStats,
|
||||
initialError,
|
||||
}: IntegratedCalendarClientProps) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
// Local state
|
||||
const [events, setEvents] = useState<CalendarEventItem[]>(initialEvents);
|
||||
const [tasks, setTasks] = useState<CalendarTaskItem[]>(initialTasks);
|
||||
const [stats, setStats] = useState<CalendarSummaryStats>(initialStats);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(initialError || null);
|
||||
|
||||
// Tabs state
|
||||
const [activeTab, setActiveTab] = useState<'events' | 'tasks'>('events');
|
||||
|
||||
// Modals state
|
||||
const [eventModalOpen, setEventModalOpen] = useState(false);
|
||||
const [selectedEvent, setSelectedEvent] = useState<CalendarEventItem | null>(null);
|
||||
|
||||
const [taskModalOpen, setTaskModalOpen] = useState(false);
|
||||
const [selectedTask, setSelectedTask] = useState<CalendarTaskItem | null>(null);
|
||||
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [deleteItem, setDeleteItem] = useState<{
|
||||
id: string;
|
||||
title: string;
|
||||
type: 'event' | 'task';
|
||||
} | null>(null);
|
||||
|
||||
const [togglingTaskId, setTogglingTaskId] = useState<string | null>(null);
|
||||
|
||||
// Refresh handler
|
||||
const handleRefresh = async () => {
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const [evRes, taskRes, statsRes] = await Promise.all([
|
||||
getCalendarEvents(),
|
||||
getCalendarTasks(),
|
||||
getCalendarSummaryStats(),
|
||||
]);
|
||||
|
||||
if (evRes.success && evRes.data) {
|
||||
setEvents(evRes.data);
|
||||
setErrorMessage(null);
|
||||
} else if (evRes.error) {
|
||||
setErrorMessage(evRes.error);
|
||||
}
|
||||
|
||||
if (taskRes.success && taskRes.data) {
|
||||
setTasks(taskRes.data);
|
||||
}
|
||||
|
||||
if (statsRes.success && statsRes.data) {
|
||||
setStats(statsRes.data);
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
toast.info('Data kalender berhasil dimuat ulang.');
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Gagal memuat ulang data.';
|
||||
toast.error(msg);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Event actions
|
||||
const handleAddEvent = () => {
|
||||
setSelectedEvent(null);
|
||||
setEventModalOpen(true);
|
||||
};
|
||||
|
||||
const handleEditEvent = (event: CalendarEventItem) => {
|
||||
setSelectedEvent(event);
|
||||
setEventModalOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteEvent = (event: CalendarEventItem) => {
|
||||
setDeleteItem({
|
||||
id: event.id,
|
||||
title: event.summary,
|
||||
type: 'event',
|
||||
});
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// Task actions
|
||||
const handleAddTask = () => {
|
||||
setSelectedTask(null);
|
||||
setTaskModalOpen(true);
|
||||
};
|
||||
|
||||
const handleEditTask = (task: CalendarTaskItem) => {
|
||||
setSelectedTask(task);
|
||||
setTaskModalOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteTask = (task: CalendarTaskItem) => {
|
||||
setDeleteItem({
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
type: 'task',
|
||||
});
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// Quick toggle task status
|
||||
const handleToggleTaskStatus = async (task: CalendarTaskItem, newStatus: TaskStatus) => {
|
||||
try {
|
||||
setTogglingTaskId(task.id);
|
||||
|
||||
// Optimistic local update
|
||||
setTasks((prev) =>
|
||||
prev.map((t) => (t.id === task.id ? { ...t, status: newStatus } : t))
|
||||
);
|
||||
|
||||
const res = await toggleCalendarTaskStatus(task.id, newStatus);
|
||||
if (res.success) {
|
||||
toast.success(
|
||||
newStatus === 'completed'
|
||||
? 'Task ditandai SELESAI di Google Calendar!'
|
||||
: 'Task diubah kembali ke status MENUNGGU.'
|
||||
);
|
||||
handleRefresh();
|
||||
} else {
|
||||
toast.error(res.error || 'Gagal mengubah status task.');
|
||||
// Revert
|
||||
setTasks((prev) =>
|
||||
prev.map((t) => (t.id === task.id ? { ...t, status: task.status } : t))
|
||||
);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Terjadi kesalahan sistem.';
|
||||
toast.error(msg);
|
||||
setTasks((prev) =>
|
||||
prev.map((t) => (t.id === task.id ? { ...t, status: task.status } : t))
|
||||
);
|
||||
} finally {
|
||||
setTogglingTaskId(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-4 sm:p-6 lg:p-8 max-w-7xl mx-auto">
|
||||
{/* Header */}
|
||||
<CalendarHeader
|
||||
calendarId={stats.calendarId}
|
||||
serviceAccountEmail={stats.serviceAccountEmail}
|
||||
onRefresh={handleRefresh}
|
||||
onAddEvent={handleAddEvent}
|
||||
onAddTask={handleAddTask}
|
||||
isRefreshing={isPending}
|
||||
/>
|
||||
|
||||
{/* Error / API Disabled Notice */}
|
||||
<ApiNoticeBanner error={errorMessage} />
|
||||
|
||||
{/* Stats Cards */}
|
||||
<CalendarStatsOverview
|
||||
totalEvents={events.length}
|
||||
totalTasks={tasks.length}
|
||||
completedTasks={tasks.filter((t) => t.status === 'completed').length}
|
||||
pendingTasks={tasks.filter((t) => t.status === 'needsAction').length}
|
||||
/>
|
||||
|
||||
{/* Main Content Tabs: Events vs Tasks */}
|
||||
<div className="space-y-4">
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={(val) => setActiveTab(val as 'events' | 'tasks')}
|
||||
className="w-full"
|
||||
>
|
||||
<div className="flex items-center justify-between border-b border-zinc-200 dark:border-zinc-800 pb-2">
|
||||
<TabsList className="bg-zinc-100 dark:bg-zinc-800/80 p-1 rounded-lg">
|
||||
<TabsTrigger
|
||||
value="events"
|
||||
className="flex items-center gap-2 text-xs sm:text-sm font-medium py-1.5 px-3 data-[state=active]:bg-white dark:data-[state=active]:bg-zinc-900 data-[state=active]:shadow-xs rounded-md"
|
||||
>
|
||||
<Calendar className="size-4" />
|
||||
<span>Events Kalender</span>
|
||||
<span className="text-xs px-1.5 py-0.2 bg-zinc-200 dark:bg-zinc-700 rounded-full font-semibold">
|
||||
{events.length}
|
||||
</span>
|
||||
</TabsTrigger>
|
||||
|
||||
<TabsTrigger
|
||||
value="tasks"
|
||||
className="flex items-center gap-2 text-xs sm:text-sm font-medium py-1.5 px-3 data-[state=active]:bg-white dark:data-[state=active]:bg-zinc-900 data-[state=active]:shadow-xs rounded-md"
|
||||
>
|
||||
<ListTodo className="size-4" />
|
||||
<span>Task Kalender</span>
|
||||
<span className="text-xs px-1.5 py-0.2 bg-zinc-200 dark:bg-zinc-700 rounded-full font-semibold">
|
||||
{tasks.length}
|
||||
</span>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<TabsContent value="events" className="mt-4 focus-visible:outline-none">
|
||||
<EventList
|
||||
events={events}
|
||||
onEdit={handleEditEvent}
|
||||
onDelete={handleDeleteEvent}
|
||||
onAddEvent={handleAddEvent}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="tasks" className="mt-4 focus-visible:outline-none">
|
||||
<TaskList
|
||||
tasks={tasks}
|
||||
onToggleStatus={handleToggleTaskStatus}
|
||||
onEdit={handleEditTask}
|
||||
onDelete={handleDeleteTask}
|
||||
onAddTask={handleAddTask}
|
||||
isTogglingId={togglingTaskId}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{/* Modals */}
|
||||
<EventFormModal
|
||||
open={eventModalOpen}
|
||||
onOpenChange={setEventModalOpen}
|
||||
event={selectedEvent}
|
||||
onSuccess={handleRefresh}
|
||||
/>
|
||||
|
||||
<TaskFormModal
|
||||
open={taskModalOpen}
|
||||
onOpenChange={setTaskModalOpen}
|
||||
task={selectedTask}
|
||||
onSuccess={handleRefresh}
|
||||
/>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={setDeleteDialogOpen}
|
||||
item={deleteItem}
|
||||
onSuccess={handleRefresh}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { CalendarTaskItem, TaskStatus } from '@/lib/google-calendar/types';
|
||||
import { createCalendarTask, updateCalendarTask } from '@/lib/google-calendar/tasks.actions';
|
||||
import { toast } from 'sonner';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface TaskFormModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
task?: CalendarTaskItem | null;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
interface FormInnerProps {
|
||||
task?: CalendarTaskItem | null;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
function TaskFormInner({ task, onClose, onSuccess }: FormInnerProps) {
|
||||
const isEdit = !!task;
|
||||
|
||||
const defaultDue = task
|
||||
? task.due.includes('T')
|
||||
? dayjs(task.due).format('YYYY-MM-DDTHH:mm')
|
||||
: dayjs(task.due).format('YYYY-MM-DD')
|
||||
: dayjs().add(1, 'day').hour(17).minute(0).second(0).format('YYYY-MM-DDTHH:mm');
|
||||
|
||||
const [title, setTitle] = useState(task?.title || '');
|
||||
const [description, setDescription] = useState(task?.description || '');
|
||||
const [due, setDue] = useState(defaultDue);
|
||||
const [status, setStatus] = useState<TaskStatus>(task?.status || 'needsAction');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!title.trim()) {
|
||||
toast.error('Judul task wajib diisi!');
|
||||
return;
|
||||
}
|
||||
if (!due) {
|
||||
toast.error('Tenggat waktu task wajib diisi!');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
if (isEdit && task) {
|
||||
const res = await updateCalendarTask(task.id, {
|
||||
title,
|
||||
description,
|
||||
due,
|
||||
status,
|
||||
});
|
||||
|
||||
if (res.success) {
|
||||
toast.success('Task berhasil diperbarui di Google Calendar!');
|
||||
onClose();
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(res.error || 'Gagal memperbarui task.');
|
||||
}
|
||||
} else {
|
||||
const res = await createCalendarTask({
|
||||
title,
|
||||
description,
|
||||
due,
|
||||
status,
|
||||
});
|
||||
|
||||
if (res.success) {
|
||||
toast.success('Task berhasil ditambahkan ke Google Calendar!');
|
||||
onClose();
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(res.error || 'Gagal membuat task.');
|
||||
}
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Terjadi kesalahan sistem.';
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col">
|
||||
<DialogHeader className="p-6 pb-4 border-b border-zinc-100 dark:border-zinc-800">
|
||||
<DialogTitle className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
{isEdit ? 'Edit Task Kalender' : 'Tambah Task Baru'}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400">
|
||||
Task akan disimpan sebagai agenda berlabel [TASK] pada kalender Google resmi.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
|
||||
{/* Title */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="task-title" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Judul Task <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="task-title"
|
||||
placeholder="misal: Finalisasi Laporan Bulanan"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Due Date & Time */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="task-due" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Tenggat Waktu (Due Date) <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="task-due"
|
||||
type="datetime-local"
|
||||
value={due}
|
||||
onChange={(e) => setDue(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
className="h-9 text-xs sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Option */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Status Pengerjaan
|
||||
</Label>
|
||||
<div className="grid grid-cols-2 gap-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatus('needsAction')}
|
||||
className={`flex items-center justify-center py-2 px-3 rounded-lg border text-xs font-medium transition-all ${status === 'needsAction'
|
||||
? 'border-amber-500 bg-amber-50/70 text-amber-900 dark:border-amber-600 dark:bg-amber-950/40 dark:text-amber-200'
|
||||
: 'border-zinc-200 dark:border-zinc-800 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-50 dark:hover:bg-zinc-900'
|
||||
}`}
|
||||
>
|
||||
Menunggu (needsAction)
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatus('completed')}
|
||||
className={`flex items-center justify-center py-2 px-3 rounded-lg border text-xs font-medium transition-all ${status === 'completed'
|
||||
? 'border-emerald-500 bg-emerald-50/70 text-emerald-900 dark:border-emerald-600 dark:bg-emerald-950/40 dark:text-emerald-200'
|
||||
: 'border-zinc-200 dark:border-zinc-800 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-50 dark:hover:bg-zinc-900'
|
||||
}`}
|
||||
>
|
||||
Selesai (completed)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description / Notes */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="task-description" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Catatan / Detail Task (Opsional)
|
||||
</Label>
|
||||
<Textarea
|
||||
id="task-description"
|
||||
placeholder="Rincian checklist atau catatan tugas..."
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
disabled={loading}
|
||||
rows={3}
|
||||
className="text-xs sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="p-4 bg-zinc-50 dark:bg-zinc-900/50 border-t border-zinc-100 dark:border-zinc-800 flex items-center justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
Batal
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
className="bg-emerald-600 hover:bg-emerald-700 text-white font-medium"
|
||||
>
|
||||
{loading && <Loader2 className="size-3.5 mr-1.5 animate-spin" />}
|
||||
{isEdit ? 'Simpan Perubahan' : 'Buat Task'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export default function TaskFormModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
task,
|
||||
onSuccess,
|
||||
}: TaskFormModalProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden bg-white dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
|
||||
{open && (
|
||||
<TaskFormInner
|
||||
key={task?.id || 'new'}
|
||||
task={task}
|
||||
onClose={() => onOpenChange(false)}
|
||||
onSuccess={onSuccess}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { CalendarTaskItem, TaskStatus } from '@/lib/google-calendar/types';
|
||||
import { ListTodo, CheckCircle2, Clock, Edit2, Trash2, Search, ExternalLink } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface TaskListProps {
|
||||
tasks: CalendarTaskItem[];
|
||||
onToggleStatus: (task: CalendarTaskItem, newStatus: TaskStatus) => void;
|
||||
onEdit: (task: CalendarTaskItem) => void;
|
||||
onDelete: (task: CalendarTaskItem) => void;
|
||||
onAddTask: () => void;
|
||||
isTogglingId?: string | null;
|
||||
}
|
||||
|
||||
export default function TaskList({
|
||||
tasks,
|
||||
onToggleStatus,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onAddTask,
|
||||
isTogglingId,
|
||||
}: TaskListProps) {
|
||||
const [search, setSearch] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState<'all' | 'needsAction' | 'completed'>('all');
|
||||
|
||||
const filtered = tasks.filter((t) => {
|
||||
const q = search.toLowerCase();
|
||||
const matchSearch =
|
||||
t.title.toLowerCase().includes(q) ||
|
||||
(t.description && t.description.toLowerCase().includes(q));
|
||||
|
||||
if (!matchSearch) return false;
|
||||
|
||||
if (statusFilter === 'all') return true;
|
||||
return t.status === statusFilter;
|
||||
});
|
||||
|
||||
const formatDue = (dueStr: string) => {
|
||||
if (!dueStr) return '-';
|
||||
if (!dueStr.includes('T')) {
|
||||
return dayjs(dueStr).format('DD MMM YYYY');
|
||||
}
|
||||
return dayjs(dueStr).format('DD MMM YYYY, HH:mm') + ' WIB';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Controls: Search & Filter Tabs */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-zinc-400 pointer-events-none" />
|
||||
<Input
|
||||
placeholder="Cari task..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-9 h-9 text-xs sm:text-sm bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 bg-zinc-100 dark:bg-zinc-800/80 p-1 rounded-lg self-start sm:self-auto">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('all')}
|
||||
className={`px-2.5 py-1 text-xs rounded-md font-medium transition-colors ${
|
||||
statusFilter === 'all'
|
||||
? 'bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 shadow-xs'
|
||||
: 'text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200'
|
||||
}`}
|
||||
>
|
||||
Semua ({tasks.length})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('needsAction')}
|
||||
className={`px-2.5 py-1 text-xs rounded-md font-medium transition-colors ${
|
||||
statusFilter === 'needsAction'
|
||||
? 'bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 shadow-xs'
|
||||
: 'text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200'
|
||||
}`}
|
||||
>
|
||||
Menunggu ({tasks.filter((t) => t.status === 'needsAction').length})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('completed')}
|
||||
className={`px-2.5 py-1 text-xs rounded-md font-medium transition-colors ${
|
||||
statusFilter === 'completed'
|
||||
? 'bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 shadow-xs'
|
||||
: 'text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200'
|
||||
}`}
|
||||
>
|
||||
Selesai ({tasks.filter((t) => t.status === 'completed').length})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* List Container */}
|
||||
{filtered.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-zinc-300 dark:border-zinc-800 p-8 text-center bg-zinc-50/50 dark:bg-zinc-900/30">
|
||||
<ListTodo className="size-10 text-zinc-400 mx-auto mb-3 stroke-[1.5]" />
|
||||
<h3 className="text-sm font-semibold text-zinc-800 dark:text-zinc-200">
|
||||
{tasks.length === 0 ? 'Belum Ada Task Kalender' : 'Tidak Ada Task yang Sesuai Filter'}
|
||||
</h3>
|
||||
<p className="text-xs text-zinc-500 max-w-sm mx-auto mt-1 mb-4">
|
||||
{tasks.length === 0
|
||||
? 'Tambahkan task pertama Anda. Task akan diberi penanda khusus [TASK] pada Google Calendar resmi.'
|
||||
: 'Silakan reset pencarian atau filter status untuk melihat data lain.'}
|
||||
</p>
|
||||
{tasks.length === 0 && (
|
||||
<Button size="sm" onClick={onAddTask} className="h-9">
|
||||
Tambah Task Pertama
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2.5">
|
||||
{filtered.map((item) => {
|
||||
const isCompleted = item.status === 'completed';
|
||||
const isProcessing = isTogglingId === item.id;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`group flex flex-col md:flex-row md:items-center justify-between p-4 rounded-xl border transition-colors shadow-xs gap-3 ${
|
||||
isCompleted
|
||||
? 'border-zinc-200/60 dark:border-zinc-800/50 bg-zinc-50/60 dark:bg-zinc-900/40 opacity-85'
|
||||
: 'border-zinc-200 dark:border-zinc-800/80 bg-white dark:bg-zinc-900 hover:border-zinc-300 dark:hover:border-zinc-700'
|
||||
}`}
|
||||
>
|
||||
{/* Checkbox & Task Details */}
|
||||
<div className="flex items-start gap-3 flex-1 min-w-0">
|
||||
<div className="pt-0.5">
|
||||
<Checkbox
|
||||
checked={isCompleted}
|
||||
disabled={isProcessing}
|
||||
onCheckedChange={(checked) => {
|
||||
onToggleStatus(item, checked ? 'completed' : 'needsAction');
|
||||
}}
|
||||
className="size-5 rounded-md border-zinc-300 dark:border-zinc-700 data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h4
|
||||
className={`font-semibold text-sm sm:text-base truncate ${
|
||||
isCompleted
|
||||
? 'line-through text-zinc-500 dark:text-zinc-400'
|
||||
: 'text-zinc-900 dark:text-zinc-100'
|
||||
}`}
|
||||
>
|
||||
{item.title}
|
||||
</h4>
|
||||
|
||||
{isCompleted ? (
|
||||
<Badge variant="statusSuccess" className="text-[10px] py-0 px-2 gap-1">
|
||||
<CheckCircle2 className="size-3" />
|
||||
<span>Selesai</span>
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="statusWarning" className="text-[10px] py-0 px-2 gap-1">
|
||||
<Clock className="size-3" />
|
||||
<span>Menunggu</span>
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-zinc-500 dark:text-zinc-400">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="size-3.5 text-zinc-400" />
|
||||
<span>Tenggat: {formatDue(item.due)}</span>
|
||||
</div>
|
||||
{item.completedAt && (
|
||||
<span className="text-[11px] text-zinc-400">
|
||||
(Diselesaikan {dayjs(item.completedAt).format('DD MMM YYYY, HH:mm')})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{item.description && (
|
||||
<p className="text-xs text-zinc-600 dark:text-zinc-300 line-clamp-2 pt-0.5">
|
||||
{item.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center gap-1.5 self-end md:self-center shrink-0 pt-2 md:pt-0 border-t md:border-t-0 border-zinc-100 dark:border-zinc-800/60 w-full md:w-auto justify-end">
|
||||
{item.htmlLink && (
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"
|
||||
title="Lihat di Google Calendar"
|
||||
>
|
||||
<a href={item.htmlLink} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="size-3.5" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onEdit(item)}
|
||||
className="h-8 px-2.5 text-xs text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<Edit2 className="size-3 mr-1" />
|
||||
<span>Edit</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onDelete(item)}
|
||||
className="h-8 px-2.5 text-xs border-rose-200 text-rose-600 hover:bg-rose-50 dark:border-rose-900/60 dark:text-rose-400 dark:hover:bg-rose-950/40"
|
||||
>
|
||||
<Trash2 className="size-3 mr-1" />
|
||||
<span>Hapus</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { getCalendarEvents } from '@/lib/google-calendar/events.actions';
|
||||
import { getCalendarTasks, getCalendarSummaryStats } from '@/lib/google-calendar/tasks.actions';
|
||||
import IntegratedCalendarClient from './components/IntegratedCalendarClient';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Integrated Google Calendar & Task - HIS Attendance Task System (H.A.T.s)',
|
||||
description: 'Pengujian integrasi langsung Server-to-Server Google Calendar API dan Tasks dengan Service Account.',
|
||||
};
|
||||
|
||||
export default async function IntegratedCalendarPage() {
|
||||
// Fetch initial data in parallel on the server
|
||||
const [eventsRes, tasksRes, statsRes] = await Promise.all([
|
||||
getCalendarEvents(),
|
||||
getCalendarTasks(),
|
||||
getCalendarSummaryStats(),
|
||||
]);
|
||||
|
||||
const initialEvents = eventsRes.data || [];
|
||||
const initialTasks = tasksRes.data || [];
|
||||
|
||||
const initialStats = statsRes.data || {
|
||||
totalEvents: initialEvents.length,
|
||||
totalTasks: initialTasks.length,
|
||||
completedTasks: initialTasks.filter((t) => t.status === 'completed').length,
|
||||
pendingTasks: initialTasks.filter((t) => t.status === 'needsAction').length,
|
||||
calendarId: process.env.GOOGLE_CALENDAR_ID || '',
|
||||
serviceAccountEmail: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL || '',
|
||||
};
|
||||
|
||||
const initialError = eventsRes.error || tasksRes.error || statsRes.error || null;
|
||||
|
||||
return (
|
||||
<IntegratedCalendarClient
|
||||
initialEvents={initialEvents}
|
||||
initialTasks={initialTasks}
|
||||
initialStats={initialStats}
|
||||
initialError={initialError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user