feat: enhance DateService with timezone support and improved date manipulation methods
This commit is contained in:
@@ -35,7 +35,7 @@ export const Primary: Story = {
|
||||
name: 'Button',
|
||||
args: {
|
||||
children: 'Hello',
|
||||
type: 'button',
|
||||
type: 'submit',
|
||||
style: {
|
||||
color: 'blue',
|
||||
border: '1px solid gray',
|
||||
|
||||
@@ -1,47 +1,53 @@
|
||||
import { DateService } from '@repo/utils';
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
|
||||
// Mock Data untuk simulasi list tugas/tagihan
|
||||
// Kita gunakan relative time agar mock data selalu relevan saat dijalankan
|
||||
const MOCK_TASKS = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Bayar Server (Lusa)',
|
||||
dueDate: DateService.now().add(2, 'day').toISOString(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Laporan Bulanan (Lewat 5 Hari)',
|
||||
dueDate: DateService.now().subtract(5, 'day').toISOString(),
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'Meeting Tahunan (Bulan Depan)',
|
||||
dueDate: DateService.now().add(1, 'month').toISOString(),
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: 'Deadline Besok Pagi',
|
||||
dueDate: DateService.now().add(1, 'day').startOf('day').toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
export const DateServiceExample: React.FC = () => {
|
||||
// 1. STATE: Waktu sekarang (untuk jam digital)
|
||||
const [currentTime, setCurrentTime] = useState<DateService>(DateService.now());
|
||||
// --- 0. TIMEZONE CONFIGURATION (ROOT CONTROL) ---
|
||||
const [currentZone, setCurrentZone] = useState<string>(DateService.getGlobalTimezone());
|
||||
|
||||
// 2. STATE: Manipulasi tanggal interaktif
|
||||
// Ambil list timezone dari helper static yang kita buat sebelumnya
|
||||
const timezoneList = useMemo(() => DateService.getSupportedTimezones(), []);
|
||||
|
||||
// --- 1. STATE & DATA ---
|
||||
|
||||
// MOCK DATA dipindahkan ke sini & pakai useMemo
|
||||
// Agar saat timezone ganti, tasks ini di-regenerate dengan waktu "Now" versi timezone baru.
|
||||
const tasks = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Bayar Server (Lusa)',
|
||||
dueDate: DateService.now().add(2, 'day').toISOString(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Laporan Bulanan (Lewat 5 Hari)',
|
||||
dueDate: DateService.now().subtract(5, 'day').toISOString(),
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'Meeting Tahunan (Bulan Depan)',
|
||||
dueDate: DateService.now().add(1, 'month').toISOString(),
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: 'Deadline Besok Pagi',
|
||||
dueDate: DateService.now().add(1, 'day').startOf('day').toISOString(),
|
||||
},
|
||||
];
|
||||
}, [currentZone]); // Dependency: currentZone
|
||||
|
||||
const [currentTime, setCurrentTime] = useState<DateService>(DateService.now());
|
||||
const [selectedDate, setSelectedDate] = useState<DateService>(DateService.now());
|
||||
|
||||
// 3. STATE: Khusus Demo Logic Calendar (Besok jam 00:00 vs Sekarang)
|
||||
// Ini untuk menjawab kenapa diff kadang 0 padahal beda hari
|
||||
const [calendarTarget] = useState(() => DateService.now().add(1, 'day').startOf('day'));
|
||||
// State demo logic calendar
|
||||
const [calendarTarget, setCalendarTarget] = useState(() => DateService.now().add(1, 'day').startOf('day'));
|
||||
|
||||
// 4. MEMO: Nilai Epoch Static (Hanya diambil saat component mount)
|
||||
// Gunakan ini jika ingin nilai 'kapan user membuka halaman'
|
||||
// Static date (Memo kosong) -> Akan tetap di Timezone saat pertama kali load (kecuali di-refresh)
|
||||
// Ini bagus untuk demo bahwa object lama tidak berubah (immutable) kecuali dibuat ulang.
|
||||
const staticDate = useMemo(() => new DateService(), []);
|
||||
|
||||
// Effect untuk update jam setiap detik
|
||||
// Effect update jam tiap detik
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
setCurrentTime(DateService.now());
|
||||
@@ -49,25 +55,79 @@ export const DateServiceExample: React.FC = () => {
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// Handler untuk tombol tambah/kurang hari
|
||||
// --- HANDLER GANTI TIMEZONE ---
|
||||
const handleZoneChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const newZone = e.target.value;
|
||||
setCurrentZone(newZone);
|
||||
|
||||
// 1. Set Global Config (Inti Perubahan)
|
||||
DateService.setGlobalConfig(newZone);
|
||||
|
||||
// 2. Force Refresh State agar UI langsung berubah
|
||||
// Kita buat instance baru agar mengambil config timezone terbaru
|
||||
setCurrentTime(DateService.now());
|
||||
|
||||
// Kita recreate selectedDate dengan nilai raw yang sama, tapi context timezone baru
|
||||
setSelectedDate((prev) => new DateService(prev.getRaw()));
|
||||
|
||||
// Recreate target demo calendar
|
||||
setCalendarTarget(DateService.now().add(1, 'day').startOf('day'));
|
||||
};
|
||||
|
||||
const handleAddDay = (days: number) => {
|
||||
setSelectedDate((prev) => prev.add(days, 'day'));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-8 max-w-5xl mx-auto bg-gray-50 min-h-screen font-sans text-gray-800">
|
||||
<h1 className="text-3xl font-bold mb-8 text-blue-900">DateService Feature Showcase</h1>
|
||||
{/* HEADER & TIMEZONE CONTROLLER */}
|
||||
<div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4 border-b border-gray-200 pb-6">
|
||||
<h1 className="text-3xl font-bold text-blue-900">DateService Feature Showcase</h1>
|
||||
|
||||
<div className="bg-white p-3 rounded-lg shadow-sm border border-blue-100 flex items-center gap-3">
|
||||
<label htmlFor="tz-switcher" className="text-xs font-bold text-gray-500 uppercase tracking-wide">
|
||||
App Timezone:
|
||||
</label>
|
||||
<select
|
||||
id="tz-switcher"
|
||||
value={currentZone}
|
||||
onChange={handleZoneChange}
|
||||
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 block p-1.5 outline-none font-mono"
|
||||
>
|
||||
{timezoneList.map((tz) => (
|
||||
<option key={tz} value={tz}>
|
||||
{tz}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* --- CARD 1: REALTIME CLOCK --- */}
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 flex flex-col justify-between">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-2">Realtime Clock</h2>
|
||||
<div className="text-4xl font-mono font-bold text-gray-900">{currentTime.format('HH:mm:ss')}</div>
|
||||
<div className="text-lg text-gray-500 mt-1">{currentTime.format('dddd, DD MMMM YYYY')}</div>
|
||||
|
||||
<div className="flex flex-col">
|
||||
<div className="text-4xl font-mono font-bold text-gray-900">{currentTime.format('HH:mm:ss')}</div>
|
||||
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
{/* UPDATE DI SINI: Gunakan .timezoneAbbr */}
|
||||
<div className="text-sm font-bold text-blue-700 bg-blue-100 px-2 py-1 rounded border border-blue-200">
|
||||
{/* Ini akan output "WIB", "WITA", atau "EST" */}
|
||||
{currentTime.timezoneAbbr}
|
||||
|
||||
{/* Ini offset angka (+07:00) */}
|
||||
<span className="opacity-60 text-xs ml-1">({currentTime.format('Z')})</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-lg text-gray-500 mt-2">{currentTime.format('dddd, DD MMMM YYYY')}</div>
|
||||
</div>
|
||||
<div className="mt-4 text-xs bg-gray-100 p-2 rounded text-gray-500 font-mono break-all">
|
||||
ISO: {currentTime.toISOString()}
|
||||
ISO (UTC): {currentTime.toISOString()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -79,7 +139,7 @@ export const DateServiceExample: React.FC = () => {
|
||||
{/* STATIC SECTION */}
|
||||
<div className="bg-blue-50 p-3 rounded-lg border border-blue-100">
|
||||
<div className="text-xs font-bold text-blue-800 mb-1">STATIC (Load Once)</div>
|
||||
<div className="text-xs text-blue-600 mb-2">Captured via useMemo([]), tidak berubah.</div>
|
||||
<div className="text-xs text-blue-600 mb-2">Captured on mount (keeps original timezone).</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||
@@ -95,7 +155,7 @@ export const DateServiceExample: React.FC = () => {
|
||||
{/* LIVE SECTION */}
|
||||
<div className="bg-green-50 p-3 rounded-lg border border-green-100">
|
||||
<div className="text-xs font-bold text-green-800 mb-1">LIVE (Reactive)</div>
|
||||
<div className="text-xs text-green-600 mb-2">Updated every second (new instance).</div>
|
||||
<div className="text-xs text-green-600 mb-2">Updated every second (follows dropdown).</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||
@@ -110,49 +170,44 @@ export const DateServiceExample: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 3: CALENDAR LOGIC DEMO (Standard vs Calendar Diff) --- */}
|
||||
{/* --- CARD 3: CALENDAR LOGIC DEMO --- */}
|
||||
<div className="bg-indigo-50 p-6 rounded-xl shadow-sm border border-indigo-200 md:col-span-2">
|
||||
<h2 className="text-lg font-bold text-indigo-900 mb-4 flex items-center gap-2">
|
||||
🗓️ Calendar Logic Demo (The "Zero Day" Issue)
|
||||
</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
{/* Info Section */}
|
||||
<div className="text-sm text-indigo-800 space-y-2">
|
||||
<p>
|
||||
Compare <strong>Current Time</strong> vs <strong>Tomorrow 00:00</strong>.
|
||||
</p>
|
||||
<div className="bg-white/50 p-2 rounded">
|
||||
<div className="flex justify-between text-xs">
|
||||
<span>Now:</span>
|
||||
<span>Now ({currentZone}):</span>
|
||||
<span className="font-mono font-bold">{currentTime.format('HH:mm')}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-xs mt-1">
|
||||
<span>Target:</span>
|
||||
<span>Target (Start of Day):</span>
|
||||
<span className="font-mono font-bold">{calendarTarget.format('DD MMM HH:mm')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Wrong Way */}
|
||||
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-red-400">
|
||||
<div className="text-xs text-gray-400 uppercase font-bold">Standard .diff('day')</div>
|
||||
<div className="text-2xl font-bold text-red-600 mt-1">
|
||||
{calendarTarget.diff(currentTime, 'day')}{' '}
|
||||
<span className="text-sm font-normal text-gray-500">Days</span>
|
||||
</div>
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
Hasil 0 jika jarak < 24 jam. Kurang cocok untuk deadline "H-1".
|
||||
</p>
|
||||
<p className="text-xs text-red-500 mt-1">Hasil 0 jika jarak < 24 jam.</p>
|
||||
</div>
|
||||
|
||||
{/* Right Way */}
|
||||
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-green-500">
|
||||
<div className="text-xs text-gray-400 uppercase font-bold">New .diffCalendarDay()</div>
|
||||
<div className="text-2xl font-bold text-green-600 mt-1">
|
||||
{calendarTarget.diffCalendarDay(currentTime)}{' '}
|
||||
<span className="text-sm font-normal text-gray-500">Days</span>
|
||||
</div>
|
||||
<p className="text-xs text-green-600 mt-1">Hasil 1. Menghitung selisih tanggal kalender (ignore jam).</p>
|
||||
<p className="text-xs text-green-600 mt-1">Hasil 1. Benar secara kalender.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -174,6 +229,7 @@ export const DateServiceExample: React.FC = () => {
|
||||
<div className="flex-1 text-center">
|
||||
<span className="block text-3xl font-bold text-blue-900">{selectedDate.format('DD MMMM YYYY')}</span>
|
||||
<span className="text-sm text-blue-600 font-medium">Selected Date State</span>
|
||||
<span className="text-xs text-gray-400 block mt-1">Offset: {selectedDate.format('Z')}</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
@@ -201,9 +257,11 @@ export const DateServiceExample: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 5: TASK LIST (IMPLEMENTATION REAL) --- */}
|
||||
{/* --- CARD 5: TASK LIST (DYNAMIC) --- */}
|
||||
<div className="mt-8 bg-white p-6 rounded-xl shadow-sm border border-gray-200">
|
||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">Task List Implementation</h2>
|
||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">
|
||||
Task List Implementation (Timezone Aware)
|
||||
</h2>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
@@ -212,22 +270,16 @@ export const DateServiceExample: React.FC = () => {
|
||||
<th className="py-3 px-4 rounded-tl-lg">Task Name</th>
|
||||
<th className="py-3 px-4">Due Date</th>
|
||||
<th className="py-3 px-4">Status Badge</th>
|
||||
<th className="py-3 px-4 rounded-tr-lg">Human Readable Countdown</th>
|
||||
<th className="py-3 px-4 rounded-tr-lg">Countdown</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{MOCK_TASKS.map((task) => {
|
||||
{tasks.map((task) => {
|
||||
const dueDate = new DateService(task.dueDate);
|
||||
const now = DateService.now(); // Mengambil waktu 'live' dari state currentTime akan menyebabkan re-render tiap detik, tapi disini kita instantiate baru agar logic per baris bersih.
|
||||
const now = DateService.now();
|
||||
|
||||
// Logic 1: Apakah sudah lewat? (Check absolute timestamp)
|
||||
const isOverdue = now.isAfter(dueDate);
|
||||
|
||||
// Logic 2: Gunakan CALENDAR DIFF untuk countdown yang enak dibaca user
|
||||
// Jika pakai diff() biasa, tugas besok pagi bisa dianggap '0 days left'
|
||||
const daysDiff = dueDate.diffCalendarDay(now);
|
||||
|
||||
// Logic 3: Warning jika kurang dari 3 hari lagi (dan belum overdue)
|
||||
const isDueSoon = !isOverdue && daysDiff <= 3;
|
||||
|
||||
let statusBadge;
|
||||
@@ -256,11 +308,14 @@ export const DateServiceExample: React.FC = () => {
|
||||
return (
|
||||
<tr key={task.id} className={rowClass}>
|
||||
<td className="py-3 px-4 font-medium text-gray-700">{task.title}</td>
|
||||
<td className="py-3 px-4 text-gray-500 font-mono text-sm">{dueDate.format('DD MMM YYYY HH:mm')}</td>
|
||||
<td className="py-3 px-4 text-gray-500 font-mono text-sm">
|
||||
{dueDate.format('DD MMM YYYY HH:mm')}
|
||||
<span className="text-[10px] text-gray-400 ml-1">{dueDate.format('Z')}</span>
|
||||
</td>
|
||||
<td className="py-3 px-4">{statusBadge}</td>
|
||||
<td className="py-3 px-4 text-sm text-gray-600 font-medium">
|
||||
{isOverdue ? (
|
||||
`${Math.abs(daysDiff)} days late` // Gunakan Math.abs karena diff negatif
|
||||
`${Math.abs(daysDiff)} days late`
|
||||
) : daysDiff === 0 ? (
|
||||
<span className="text-amber-600">Today!</span>
|
||||
) : (
|
||||
|
||||
Reference in New Issue
Block a user