feat: add encryption and date service utilities
- Implemented EncryptionService for secure data handling with AES encryption. - Created DateService for advanced date manipulation and formatting. - Developed EncryptionDemo and DateServiceComponent for interactive demonstrations. - Added LocalStorage demo for encrypted data storage and retrieval. - Established ESLint and TypeScript configurations for utils package. - Included example utility function for demonstration purposes.
This commit is contained in:
@@ -11,6 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@repo/ui": "workspace:*",
|
||||
"@repo/utils": "workspace:*",
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
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());
|
||||
|
||||
// 2. STATE: Manipulasi tanggal interaktif
|
||||
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'));
|
||||
|
||||
// 4. MEMO: Nilai Epoch Static (Hanya diambil saat component mount)
|
||||
// Gunakan ini jika ingin nilai 'kapan user membuka halaman'
|
||||
const staticDate = useMemo(() => new DateService(), []);
|
||||
|
||||
// Effect untuk update jam setiap detik
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
setCurrentTime(DateService.now());
|
||||
}, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// Handler untuk tombol tambah/kurang hari
|
||||
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>
|
||||
|
||||
<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>
|
||||
<div className="mt-4 text-xs bg-gray-100 p-2 rounded text-gray-500 font-mono break-all">
|
||||
ISO: {currentTime.toISOString()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 2: EPOCH & TIMESTAMPS --- */}
|
||||
<div className="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">Epoch / Timestamp Data</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* 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="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||
<div className="font-mono font-bold text-gray-700">{staticDate.epochMillis}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Seconds</div>
|
||||
<div className="font-mono font-bold text-gray-700">{staticDate.epochSeconds}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 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="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||
<div className="font-mono font-bold text-gray-700">{new DateService().epochMillis}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Seconds</div>
|
||||
<div className="font-mono font-bold text-gray-700">{new DateService().epochSeconds}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 3: CALENDAR LOGIC DEMO (Standard vs Calendar Diff) --- */}
|
||||
<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 className="font-mono font-bold">{currentTime.format('HH:mm')}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-xs mt-1">
|
||||
<span>Target:</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>
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 4: MANIPULATION --- */}
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 md:col-span-2">
|
||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">
|
||||
Interactive Manipulation
|
||||
</h2>
|
||||
|
||||
<div className="flex flex-col md:flex-row items-center gap-4 bg-gray-50 p-4 rounded-lg mb-4">
|
||||
<button
|
||||
onClick={() => handleAddDay(-1)}
|
||||
className="px-4 py-2 bg-white border border-gray-300 shadow-sm text-gray-700 rounded hover:bg-gray-100 transition font-medium"
|
||||
>
|
||||
- 1 Day
|
||||
</button>
|
||||
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => handleAddDay(1)}
|
||||
className="px-4 py-2 bg-white border border-gray-300 shadow-sm text-gray-700 rounded hover:bg-gray-100 transition font-medium"
|
||||
>
|
||||
+ 1 Day
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4 text-center">
|
||||
<div className="bg-gray-100 p-2 rounded">
|
||||
<span className="text-xs text-gray-500 block">Precise Diff (Float)</span>
|
||||
<span className="font-mono font-bold text-gray-700">
|
||||
{selectedDate.diff(currentTime, 'day', true).toFixed(2)} days
|
||||
</span>
|
||||
</div>
|
||||
<div className="bg-gray-100 p-2 rounded">
|
||||
<span className="text-xs text-gray-500 block">Calendar Diff (Int)</span>
|
||||
<span className="font-mono font-bold text-gray-700">
|
||||
{selectedDate.diffCalendarDay(currentTime)} days
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 5: TASK LIST (IMPLEMENTATION REAL) --- */}
|
||||
<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>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="text-xs text-gray-500 border-b border-gray-100 bg-gray-50/50">
|
||||
<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>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{MOCK_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.
|
||||
|
||||
// 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;
|
||||
const rowClass = 'border-b border-gray-50 hover:bg-gray-50 transition-colors';
|
||||
|
||||
if (isOverdue) {
|
||||
statusBadge = (
|
||||
<span className="px-2 py-1 text-[10px] font-bold text-red-700 bg-red-100 rounded-full border border-red-200">
|
||||
OVERDUE
|
||||
</span>
|
||||
);
|
||||
} else if (isDueSoon) {
|
||||
statusBadge = (
|
||||
<span className="px-2 py-1 text-[10px] font-bold text-amber-700 bg-amber-100 rounded-full border border-amber-200">
|
||||
DUE SOON
|
||||
</span>
|
||||
);
|
||||
} else {
|
||||
statusBadge = (
|
||||
<span className="px-2 py-1 text-[10px] font-bold text-emerald-700 bg-emerald-100 rounded-full border border-emerald-200">
|
||||
ACTIVE
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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">{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
|
||||
) : daysDiff === 0 ? (
|
||||
<span className="text-amber-600">Today!</span>
|
||||
) : (
|
||||
`${daysDiff} days left`
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
import { EncryptionService } from '@repo/utils';
|
||||
import React, { useState } from 'react';
|
||||
|
||||
export const EncryptionDemoApps: React.FC = () => {
|
||||
// --- 1. SETUP INSTANCE ---
|
||||
// Kita gunakan Singleton agar hemat memory
|
||||
const cryptoService = EncryptionService.getInstance();
|
||||
|
||||
// --- 2. STATE ---
|
||||
const [plainText, setPlainText] = useState<string>('');
|
||||
const [encryptedResult, setEncryptedResult] = useState<string>('');
|
||||
const [decryptedResult, setDecryptedResult] = useState<string>('');
|
||||
|
||||
// State untuk demo LocalStorage
|
||||
const [storageKey] = useState<string>('my_secure_token');
|
||||
const [storageValue, setStorageValue] = useState<string>('');
|
||||
const [savedStatus, setSavedStatus] = useState<string>('');
|
||||
|
||||
// --- 3. HANDLERS ---
|
||||
|
||||
const handleEncrypt = () => {
|
||||
// Panggil method encrypt dari class
|
||||
const result = cryptoService.encrypt(plainText);
|
||||
setEncryptedResult(result);
|
||||
|
||||
// Reset decrypt result biar user harus klik decrypt lagi untuk validasi
|
||||
setDecryptedResult('');
|
||||
};
|
||||
|
||||
const handleDecrypt = () => {
|
||||
// Panggil method decrypt dari class
|
||||
const original = cryptoService.decrypt(encryptedResult);
|
||||
setDecryptedResult(original);
|
||||
};
|
||||
|
||||
// --- DEMO LOCALSTORAGE ---
|
||||
const saveToStorage = () => {
|
||||
try {
|
||||
// Encrypt sebelum simpan
|
||||
const secureData = cryptoService.encrypt(storageValue);
|
||||
localStorage.setItem(storageKey, secureData);
|
||||
setSavedStatus(`Saved securely! Cipher: ${secureData.substring(0, 15)}...`);
|
||||
} catch (error) {
|
||||
setSavedStatus('Error saving data');
|
||||
}
|
||||
};
|
||||
|
||||
const loadFromStorage = () => {
|
||||
try {
|
||||
const storedData = localStorage.getItem(storageKey);
|
||||
if (!storedData) {
|
||||
setSavedStatus('No data found in storage');
|
||||
return;
|
||||
}
|
||||
// Decrypt setelah ambil
|
||||
const originalData = cryptoService.decrypt(storedData);
|
||||
setSavedStatus(`Loaded & Decrypted: "${originalData}"`);
|
||||
} catch (error) {
|
||||
setSavedStatus('Failed to decrypt storage data');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-8 max-w-4xl mx-auto bg-slate-50 min-h-screen font-sans text-slate-800">
|
||||
<h1 className="text-3xl font-bold mb-8 text-slate-900">Encryption Service Demo</h1>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
{/* === SECTION 1: INTERACTIVE PLAYGROUND === */}
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm border border-slate-200">
|
||||
<h2 className="text-lg font-bold text-indigo-600 mb-4 flex items-center gap-2">🔐 Live Playground</h2>
|
||||
|
||||
{/* INPUT */}
|
||||
<div className="mb-4">
|
||||
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Secret Message (Input)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={plainText}
|
||||
onChange={(e) => setPlainText(e.target.value)}
|
||||
placeholder="Type sensitive data here..."
|
||||
className="w-full p-2 border border-slate-300 rounded focus:ring-2 focus:ring-indigo-500 outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ACTIONS */}
|
||||
<div className="flex gap-2 mb-6">
|
||||
<button
|
||||
onClick={handleEncrypt}
|
||||
className="bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700 transition text-sm font-semibold"
|
||||
>
|
||||
Encrypt ⬇
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDecrypt}
|
||||
disabled={!encryptedResult}
|
||||
className="bg-emerald-600 text-white px-4 py-2 rounded hover:bg-emerald-700 transition text-sm font-semibold disabled:opacity-50"
|
||||
>
|
||||
Decrypt ⬆
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* OUTPUT: ENCRYPTED */}
|
||||
<div className="mb-4">
|
||||
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">
|
||||
Encrypted Output (Ciphertext)
|
||||
</label>
|
||||
<textarea
|
||||
readOnly
|
||||
value={encryptedResult}
|
||||
className="w-full p-2 bg-slate-100 border border-slate-200 rounded text-xs font-mono text-slate-600 h-24 break-all"
|
||||
placeholder="Result will appear here..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* OUTPUT: DECRYPTED */}
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Verified Decryption</label>
|
||||
<div
|
||||
className={`p-2 border rounded min-h-[40px] flex items-center ${
|
||||
decryptedResult ? 'bg-green-50 border-green-200 text-green-800' : 'bg-slate-50 border-slate-200'
|
||||
}`}
|
||||
>
|
||||
{decryptedResult || <span className="text-slate-400 italic text-sm">Waiting for decryption...</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* === SECTION 2: SECURE LOCALSTORAGE === */}
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm border border-slate-200">
|
||||
<h2 className="text-lg font-bold text-amber-600 mb-4 flex items-center gap-2">💾 Secure LocalStorage</h2>
|
||||
<p className="text-sm text-slate-600 mb-4">
|
||||
Simulasi menyimpan token auth. Data di browser storage akan terlihat acak, tapi aplikasi bisa membacanya
|
||||
kembali.
|
||||
</p>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Data to Save</label>
|
||||
<input
|
||||
type="text"
|
||||
value={storageValue}
|
||||
onChange={(e) => setStorageValue(e.target.value)}
|
||||
placeholder="e.g., Bearer eyJhbGci..."
|
||||
className="w-full p-2 border border-slate-300 rounded focus:ring-2 focus:ring-amber-500 outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={saveToStorage}
|
||||
className="bg-slate-800 text-white px-4 py-2 rounded hover:bg-slate-900 transition text-sm font-semibold flex-1"
|
||||
>
|
||||
Save Encrypted
|
||||
</button>
|
||||
<button
|
||||
onClick={loadFromStorage}
|
||||
className="bg-white border border-slate-300 text-slate-700 px-4 py-2 rounded hover:bg-slate-50 transition text-sm font-semibold flex-1"
|
||||
>
|
||||
Load & Decrypt
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* STATUS MONITOR */}
|
||||
<div className="mt-4 bg-amber-50 border border-amber-100 p-3 rounded">
|
||||
<span className="text-xs font-bold text-amber-800 uppercase block mb-1">Log / Status</span>
|
||||
<code className="text-xs text-amber-900 block break-all">{savedStatus || 'Ready...'}</code>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 pt-4 border-t border-slate-100">
|
||||
<p className="text-xs text-slate-400">
|
||||
<strong>Tips:</strong> Buka <em>Developer Tools > Application > LocalStorage</em>. Cari key{' '}
|
||||
<code>my_secure_token</code>. Kamu akan melihat string acak (encrypted), bukan teks asli.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,6 +1,9 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { Counter } from '@repo/ui';
|
||||
import { Counter, DateServiceComponent } from '@repo/ui';
|
||||
import { utilsExample } from '@repo/utils';
|
||||
import { DateServiceExample } from './example/date-example';
|
||||
import { EncryptionDemoApps } from './example/encryption-demo';
|
||||
|
||||
const AuthModule = lazy(() => import('./auth'));
|
||||
const AppModule = lazy(() => import('./modules'));
|
||||
@@ -9,6 +12,15 @@ export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<div className="bg-green-400"> test tailwind on web</div>
|
||||
<div>
|
||||
<div>test helper</div>
|
||||
<div>{utilsExample()}</div>
|
||||
</div>
|
||||
|
||||
<EncryptionDemoApps />
|
||||
<EncryptionDemoApps />
|
||||
<DateServiceExample />
|
||||
<DateServiceComponent />
|
||||
<Counter />
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<Routes>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "turbo run build",
|
||||
"build:web": "turbo run build --filter=web",
|
||||
"dev": "turbo run dev",
|
||||
"dev:web": "turbo run dev --filter=web",
|
||||
"lint": "turbo run lint",
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"@repo/utils": "workspace:*",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { utilsExample } from '@repo/utils';
|
||||
import React, { useState } from 'react';
|
||||
|
||||
export const Counter: React.FC = () => {
|
||||
@@ -5,6 +6,10 @@ export const Counter: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div className="py-4">
|
||||
<div>
|
||||
<div>test helper</div>
|
||||
<div>{utilsExample()}</div>
|
||||
</div>
|
||||
<div className="text-2xl font-semibold">tailwind on package UI</div>
|
||||
<div className="bg-red-400 text-3xl font-bold underline">100</div>
|
||||
<div className="mt-3 bg-brand-500 text-brand-800">sdsa</div>
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
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 DateServiceComponent: React.FC = () => {
|
||||
// 1. STATE: Waktu sekarang (untuk jam digital)
|
||||
const [currentTime, setCurrentTime] = useState<DateService>(DateService.now());
|
||||
|
||||
// 2. STATE: Manipulasi tanggal interaktif
|
||||
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'));
|
||||
|
||||
// 4. MEMO: Nilai Epoch Static (Hanya diambil saat component mount)
|
||||
// Gunakan ini jika ingin nilai 'kapan user membuka halaman'
|
||||
const staticDate = useMemo(() => new DateService(), []);
|
||||
|
||||
// Effect untuk update jam setiap detik
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
setCurrentTime(DateService.now());
|
||||
}, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// Handler untuk tombol tambah/kurang hari
|
||||
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>
|
||||
|
||||
<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>
|
||||
<div className="mt-4 text-xs bg-gray-100 p-2 rounded text-gray-500 font-mono break-all">
|
||||
ISO: {currentTime.toISOString()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 2: EPOCH & TIMESTAMPS --- */}
|
||||
<div className="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">Epoch / Timestamp Data</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* 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="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||
<div className="font-mono font-bold text-gray-700">{staticDate.epochMillis}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Seconds</div>
|
||||
<div className="font-mono font-bold text-gray-700">{staticDate.epochSeconds}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 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="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||
<div className="font-mono font-bold text-gray-700">{new DateService().epochMillis}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] uppercase text-gray-500">Epoch Seconds</div>
|
||||
<div className="font-mono font-bold text-gray-700">{new DateService().epochSeconds}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 3: CALENDAR LOGIC DEMO (Standard vs Calendar Diff) --- */}
|
||||
<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 className="font-mono font-bold">{currentTime.format('HH:mm')}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-xs mt-1">
|
||||
<span>Target:</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>
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 4: MANIPULATION --- */}
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 md:col-span-2">
|
||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">
|
||||
Interactive Manipulation
|
||||
</h2>
|
||||
|
||||
<div className="flex flex-col md:flex-row items-center gap-4 bg-gray-50 p-4 rounded-lg mb-4">
|
||||
<button
|
||||
onClick={() => handleAddDay(-1)}
|
||||
className="px-4 py-2 bg-white border border-gray-300 shadow-sm text-gray-700 rounded hover:bg-gray-100 transition font-medium"
|
||||
>
|
||||
- 1 Day
|
||||
</button>
|
||||
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => handleAddDay(1)}
|
||||
className="px-4 py-2 bg-white border border-gray-300 shadow-sm text-gray-700 rounded hover:bg-gray-100 transition font-medium"
|
||||
>
|
||||
+ 1 Day
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4 text-center">
|
||||
<div className="bg-gray-100 p-2 rounded">
|
||||
<span className="text-xs text-gray-500 block">Precise Diff (Float)</span>
|
||||
<span className="font-mono font-bold text-gray-700">
|
||||
{selectedDate.diff(currentTime, 'day', true).toFixed(2)} days
|
||||
</span>
|
||||
</div>
|
||||
<div className="bg-gray-100 p-2 rounded">
|
||||
<span className="text-xs text-gray-500 block">Calendar Diff (Int)</span>
|
||||
<span className="font-mono font-bold text-gray-700">
|
||||
{selectedDate.diffCalendarDay(currentTime)} days
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- CARD 5: TASK LIST (IMPLEMENTATION REAL) --- */}
|
||||
<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>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="text-xs text-gray-500 border-b border-gray-100 bg-gray-50/50">
|
||||
<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>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{MOCK_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.
|
||||
|
||||
// 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;
|
||||
const rowClass = 'border-b border-gray-50 hover:bg-gray-50 transition-colors';
|
||||
|
||||
if (isOverdue) {
|
||||
statusBadge = (
|
||||
<span className="px-2 py-1 text-[10px] font-bold text-red-700 bg-red-100 rounded-full border border-red-200">
|
||||
OVERDUE
|
||||
</span>
|
||||
);
|
||||
} else if (isDueSoon) {
|
||||
statusBadge = (
|
||||
<span className="px-2 py-1 text-[10px] font-bold text-amber-700 bg-amber-100 rounded-full border border-amber-200">
|
||||
DUE SOON
|
||||
</span>
|
||||
);
|
||||
} else {
|
||||
statusBadge = (
|
||||
<span className="px-2 py-1 text-[10px] font-bold text-emerald-700 bg-emerald-100 rounded-full border border-emerald-200">
|
||||
ACTIVE
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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">{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
|
||||
) : daysDiff === 0 ? (
|
||||
<span className="text-amber-600">Today!</span>
|
||||
) : (
|
||||
`${daysDiff} days left`
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
import { EncryptionService } from '@repo/utils';
|
||||
import React, { useState } from 'react';
|
||||
|
||||
export const EncryptionDemo: React.FC = () => {
|
||||
// --- 1. SETUP INSTANCE ---
|
||||
// Kita gunakan Singleton agar hemat memory
|
||||
const cryptoService = EncryptionService.getInstance();
|
||||
|
||||
// --- 2. STATE ---
|
||||
const [plainText, setPlainText] = useState<string>('');
|
||||
const [encryptedResult, setEncryptedResult] = useState<string>('');
|
||||
const [decryptedResult, setDecryptedResult] = useState<string>('');
|
||||
|
||||
// State untuk demo LocalStorage
|
||||
const [storageKey] = useState<string>('my_secure_token');
|
||||
const [storageValue, setStorageValue] = useState<string>('');
|
||||
const [savedStatus, setSavedStatus] = useState<string>('');
|
||||
|
||||
// --- 3. HANDLERS ---
|
||||
|
||||
const handleEncrypt = () => {
|
||||
// Panggil method encrypt dari class
|
||||
const result = cryptoService.encrypt(plainText);
|
||||
setEncryptedResult(result);
|
||||
|
||||
// Reset decrypt result biar user harus klik decrypt lagi untuk validasi
|
||||
setDecryptedResult('');
|
||||
};
|
||||
|
||||
const handleDecrypt = () => {
|
||||
// Panggil method decrypt dari class
|
||||
const original = cryptoService.decrypt(encryptedResult);
|
||||
setDecryptedResult(original);
|
||||
};
|
||||
|
||||
// --- DEMO LOCALSTORAGE ---
|
||||
const saveToStorage = () => {
|
||||
try {
|
||||
// Encrypt sebelum simpan
|
||||
const secureData = cryptoService.encrypt(storageValue);
|
||||
localStorage.setItem(storageKey, secureData);
|
||||
setSavedStatus(`Saved securely! Cipher: ${secureData.substring(0, 15)}...`);
|
||||
} catch (error) {
|
||||
setSavedStatus('Error saving data');
|
||||
}
|
||||
};
|
||||
|
||||
const loadFromStorage = () => {
|
||||
try {
|
||||
const storedData = localStorage.getItem(storageKey);
|
||||
if (!storedData) {
|
||||
setSavedStatus('No data found in storage');
|
||||
return;
|
||||
}
|
||||
// Decrypt setelah ambil
|
||||
const originalData = cryptoService.decrypt(storedData);
|
||||
setSavedStatus(`Loaded & Decrypted: "${originalData}"`);
|
||||
} catch (error) {
|
||||
setSavedStatus('Failed to decrypt storage data');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-8 max-w-4xl mx-auto bg-slate-50 min-h-screen font-sans text-slate-800">
|
||||
<h1 className="text-3xl font-bold mb-8 text-slate-900">Encryption Service Demo</h1>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
{/* === SECTION 1: INTERACTIVE PLAYGROUND === */}
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm border border-slate-200">
|
||||
<h2 className="text-lg font-bold text-indigo-600 mb-4 flex items-center gap-2">🔐 Live Playground</h2>
|
||||
|
||||
{/* INPUT */}
|
||||
<div className="mb-4">
|
||||
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Secret Message (Input)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={plainText}
|
||||
onChange={(e) => setPlainText(e.target.value)}
|
||||
placeholder="Type sensitive data here..."
|
||||
className="w-full p-2 border border-slate-300 rounded focus:ring-2 focus:ring-indigo-500 outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ACTIONS */}
|
||||
<div className="flex gap-2 mb-6">
|
||||
<button
|
||||
onClick={handleEncrypt}
|
||||
className="bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700 transition text-sm font-semibold"
|
||||
>
|
||||
Encrypt ⬇
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDecrypt}
|
||||
disabled={!encryptedResult}
|
||||
className="bg-emerald-600 text-white px-4 py-2 rounded hover:bg-emerald-700 transition text-sm font-semibold disabled:opacity-50"
|
||||
>
|
||||
Decrypt ⬆
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* OUTPUT: ENCRYPTED */}
|
||||
<div className="mb-4">
|
||||
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">
|
||||
Encrypted Output (Ciphertext)
|
||||
</label>
|
||||
<textarea
|
||||
readOnly
|
||||
value={encryptedResult}
|
||||
className="w-full p-2 bg-slate-100 border border-slate-200 rounded text-xs font-mono text-slate-600 h-24 break-all"
|
||||
placeholder="Result will appear here..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* OUTPUT: DECRYPTED */}
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Verified Decryption</label>
|
||||
<div
|
||||
className={`p-2 border rounded min-h-[40px] flex items-center ${
|
||||
decryptedResult ? 'bg-green-50 border-green-200 text-green-800' : 'bg-slate-50 border-slate-200'
|
||||
}`}
|
||||
>
|
||||
{decryptedResult || <span className="text-slate-400 italic text-sm">Waiting for decryption...</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* === SECTION 2: SECURE LOCALSTORAGE === */}
|
||||
<div className="bg-white p-6 rounded-xl shadow-sm border border-slate-200">
|
||||
<h2 className="text-lg font-bold text-amber-600 mb-4 flex items-center gap-2">💾 Secure LocalStorage</h2>
|
||||
<p className="text-sm text-slate-600 mb-4">
|
||||
Simulasi menyimpan token auth. Data di browser storage akan terlihat acak, tapi aplikasi bisa membacanya
|
||||
kembali.
|
||||
</p>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Data to Save</label>
|
||||
<input
|
||||
type="text"
|
||||
value={storageValue}
|
||||
onChange={(e) => setStorageValue(e.target.value)}
|
||||
placeholder="e.g., Bearer eyJhbGci..."
|
||||
className="w-full p-2 border border-slate-300 rounded focus:ring-2 focus:ring-amber-500 outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={saveToStorage}
|
||||
className="bg-slate-800 text-white px-4 py-2 rounded hover:bg-slate-900 transition text-sm font-semibold flex-1"
|
||||
>
|
||||
Save Encrypted
|
||||
</button>
|
||||
<button
|
||||
onClick={loadFromStorage}
|
||||
className="bg-white border border-slate-300 text-slate-700 px-4 py-2 rounded hover:bg-slate-50 transition text-sm font-semibold flex-1"
|
||||
>
|
||||
Load & Decrypt
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* STATUS MONITOR */}
|
||||
<div className="mt-4 bg-amber-50 border border-amber-100 p-3 rounded">
|
||||
<span className="text-xs font-bold text-amber-800 uppercase block mb-1">Log / Status</span>
|
||||
<code className="text-xs text-amber-900 block break-all">{savedStatus || 'Ready...'}</code>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 pt-4 border-t border-slate-100">
|
||||
<p className="text-xs text-slate-400">
|
||||
<strong>Tips:</strong> Buka <em>Developer Tools > Application > LocalStorage</em>. Cari key{' '}
|
||||
<code>my_secure_token</code>. Kamu akan melihat string acak (encrypted), bukan teks asli.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,2 +1,4 @@
|
||||
export * from "./header";
|
||||
export * from "./counter";
|
||||
export * from './header';
|
||||
export * from './counter';
|
||||
export * from './date-example';
|
||||
export * from './encryption-demo';
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/** @type {import("eslint").Linter.Config} */
|
||||
module.exports = {
|
||||
root: true,
|
||||
ignorePatterns: ['.eslintrc.cjs'],
|
||||
extends: ['@repo/eslint-config/index.js'],
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
project: true,
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@repo/utils",
|
||||
"version": "0.0.0",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"lint": "eslint \"**/*.ts\""
|
||||
},
|
||||
"dependencies": {
|
||||
"crypto-js": "^4.2.0",
|
||||
"dayjs": "^1.11.19"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@repo/eslint-config": "workspace:*",
|
||||
"@repo/typescript-config": "workspace:*",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"eslint": "^8.57.1",
|
||||
"typescript": "5.5.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import dayjs, { Dayjs, OpUnitType, ManipulateType } from 'dayjs';
|
||||
|
||||
/**
|
||||
* FIX: Tambahkan 'Dayjs' ke dalam union type ini.
|
||||
* Ini memberitahu TS bahwa input boleh berupa string, date, atau object Dayjs itu sendiri.
|
||||
*/
|
||||
export type DateInput = string | number | Date | Dayjs | null | undefined;
|
||||
|
||||
export type TimeUnit = 'day' | 'week' | 'month' | 'year' | 'hour' | 'minute' | 'second';
|
||||
|
||||
interface IDateManager {
|
||||
format(formatString?: string): string;
|
||||
add(value: number, unit: TimeUnit): IDateManager;
|
||||
subtract(value: number, unit: TimeUnit): IDateManager;
|
||||
|
||||
// Update: Parameter sekarang support DateService instance juga (untuk DX lebih baik)
|
||||
isBefore(date: DateInput | DateService): boolean;
|
||||
isAfter(date: DateInput | DateService): boolean;
|
||||
isSame(date: DateInput | DateService, unit?: TimeUnit): boolean;
|
||||
diff(date: DateInput | DateService, unit: TimeUnit, precise?: boolean): number;
|
||||
|
||||
toISOString(): string;
|
||||
toDate(): Date;
|
||||
startOf(unit: TimeUnit): IDateManager;
|
||||
endOf(unit: TimeUnit): IDateManager;
|
||||
}
|
||||
|
||||
export class DateService implements IDateManager {
|
||||
// Kita expose _date sebagai public readonly atau getter jika perlu akses raw dayjs
|
||||
// Tapi untuk strict encapsulation, keep private.
|
||||
private readonly _date: Dayjs;
|
||||
|
||||
constructor(date?: DateInput | DateService) {
|
||||
// FIX: Handle jika inputnya adalah instance dari DateService lain
|
||||
if (date instanceof DateService) {
|
||||
this._date = date.getRaw();
|
||||
} else {
|
||||
this._date = dayjs(date);
|
||||
}
|
||||
|
||||
if (!this._date.isValid()) {
|
||||
console.warn(`[DateService] Invalid date: ${date}. Fallback to now.`);
|
||||
this._date = dayjs();
|
||||
}
|
||||
}
|
||||
|
||||
// Helper internal untuk mengambil raw object (diperlukan untuk interaksi antar instance)
|
||||
public getRaw(): Dayjs {
|
||||
return this._date;
|
||||
}
|
||||
|
||||
static now(): DateService {
|
||||
return new DateService();
|
||||
}
|
||||
|
||||
// --- Implementation Methods ---
|
||||
|
||||
format(formatString: string = 'YYYY-MM-DD'): string {
|
||||
return this._date.format(formatString);
|
||||
}
|
||||
|
||||
add(value: number, unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.add(value, unit as ManipulateType));
|
||||
}
|
||||
|
||||
subtract(value: number, unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.subtract(value, unit as ManipulateType));
|
||||
}
|
||||
|
||||
// Helper private untuk normalisasi input (menangani DateService vs DateInput biasa)
|
||||
private _toDayjs(date: DateInput | DateService): Dayjs {
|
||||
if (date instanceof DateService) {
|
||||
return date.getRaw();
|
||||
}
|
||||
return dayjs(date);
|
||||
}
|
||||
|
||||
isBefore(date: DateInput | DateService): boolean {
|
||||
return this._date.isBefore(this._toDayjs(date));
|
||||
}
|
||||
|
||||
isAfter(date: DateInput | DateService): boolean {
|
||||
return this._date.isAfter(this._toDayjs(date));
|
||||
}
|
||||
|
||||
isSame(date: DateInput | DateService, unit?: TimeUnit): boolean {
|
||||
return this._date.isSame(this._toDayjs(date), unit as OpUnitType);
|
||||
}
|
||||
|
||||
diff(date: DateInput | DateService, unit: TimeUnit, precise: boolean = false): number {
|
||||
return this._date.diff(this._toDayjs(date), unit as OpUnitType, precise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Menghitung selisih HARI KALENDER.
|
||||
* Mengabaikan jam/menit, murni membandingkan tanggal.
|
||||
*/
|
||||
diffCalendarDay(date: DateInput | DateService): number {
|
||||
const target = this._toDayjs(date);
|
||||
// Reset keduanya ke jam 00:00:00 sebelum diff
|
||||
return this._date.startOf('day').diff(target.startOf('day'), 'day');
|
||||
}
|
||||
|
||||
startOf(unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.startOf(unit as OpUnitType));
|
||||
}
|
||||
|
||||
endOf(unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.endOf(unit as OpUnitType));
|
||||
}
|
||||
|
||||
toISOString(): string {
|
||||
return this._date.toISOString();
|
||||
}
|
||||
|
||||
toDate(): Date {
|
||||
return this._date.toDate();
|
||||
}
|
||||
|
||||
get timestamp(): number {
|
||||
return this._date.valueOf();
|
||||
}
|
||||
|
||||
/* Mengembalikan Epoch dalam Milliseconds (13 digit).
|
||||
* Contoh: 1704067200000
|
||||
* Gunakan ini untuk kalkulasi di Frontend JS/TS.
|
||||
*/
|
||||
get epochMillis(): number {
|
||||
return this._date.valueOf();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengembalikan Epoch dalam Seconds (10 digit).
|
||||
* Contoh: 1704067200
|
||||
* Gunakan ini untuk kirim ke Backend (PHP, Golang, Python, dll) atau JWT.
|
||||
*/
|
||||
get epochSeconds(): number {
|
||||
return this._date.unix();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export const ENC_STORAGE_KEY = 'zkwqyo3RpNEh8un2CIAs'; //TODO change value from environment
|
||||
@@ -0,0 +1,70 @@
|
||||
import { AES, enc } from 'crypto-js';
|
||||
import { ENC_STORAGE_KEY } from './encryption-key';
|
||||
|
||||
/**
|
||||
* Interface contract supaya method konsisten
|
||||
*/
|
||||
interface IEncryptionService {
|
||||
encrypt(data: string): string;
|
||||
decrypt(encryptedData: string): string;
|
||||
}
|
||||
|
||||
export class EncryptionService implements IEncryptionService {
|
||||
private readonly _key: string;
|
||||
|
||||
/**
|
||||
* @param key (Optional) Jika tidak diisi, otomatis pakai ENC_STORAGE_KEY
|
||||
*/
|
||||
constructor(key: string = ENC_STORAGE_KEY) {
|
||||
if (!key) {
|
||||
throw new Error('[EncryptionService] Encryption key is missing/empty.');
|
||||
}
|
||||
this._key = key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengenkripsi string plain text.
|
||||
*/
|
||||
public encrypt(data: string): string {
|
||||
if (!data) {
|
||||
return '';
|
||||
}
|
||||
return AES.encrypt(data, this._key).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mendekripsi string terenkripsi.
|
||||
* Mengembalikan string kosong '' jika gagal decrypt atau format salah.
|
||||
*/
|
||||
public decrypt(encryptedData: string): string {
|
||||
if (!encryptedData) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
const bytes = AES.decrypt(encryptedData, this._key);
|
||||
const originalText = bytes.toString(enc.Utf8);
|
||||
|
||||
// Validasi tambahan: jika hasil decrypt kosong, berarti key salah atau data corrupt
|
||||
if (!originalText) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return originalText;
|
||||
} catch (error) {
|
||||
console.error('[EncryptionService] Decryption failed:', error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// --- Static Helper (Singleton Pattern sederhana) ---
|
||||
// Supaya tidak perlu 'new EncryptionService()' berulang kali
|
||||
private static instance: EncryptionService;
|
||||
|
||||
public static getInstance(): EncryptionService {
|
||||
if (!EncryptionService.instance) {
|
||||
EncryptionService.instance = new EncryptionService();
|
||||
}
|
||||
return EncryptionService.instance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function utilsExample() {
|
||||
return 'This is an example utility function.';
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './encryption';
|
||||
export * from './example';
|
||||
export * from './date-service';
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "@repo/typescript-config/vite.json",
|
||||
"include": ["."],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Generated
+43
@@ -23,6 +23,9 @@ importers:
|
||||
'@repo/ui':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/ui
|
||||
'@repo/utils':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/utils
|
||||
'@tailwindcss/vite':
|
||||
specifier: ^4.1.18
|
||||
version: 4.1.18(vite@5.4.17)
|
||||
@@ -88,6 +91,9 @@ importers:
|
||||
|
||||
packages/ui:
|
||||
dependencies:
|
||||
'@repo/utils':
|
||||
specifier: workspace:*
|
||||
version: link:../utils
|
||||
'@tailwindcss/vite':
|
||||
specifier: ^4.1.18
|
||||
version: 4.1.18(vite@5.4.17)
|
||||
@@ -132,6 +138,31 @@ importers:
|
||||
specifier: ^5.1.4
|
||||
version: 5.4.17
|
||||
|
||||
packages/utils:
|
||||
dependencies:
|
||||
crypto-js:
|
||||
specifier: ^4.2.0
|
||||
version: 4.2.0
|
||||
dayjs:
|
||||
specifier: ^1.11.19
|
||||
version: 1.11.19
|
||||
devDependencies:
|
||||
'@repo/eslint-config':
|
||||
specifier: workspace:*
|
||||
version: link:../configs/eslint
|
||||
'@repo/typescript-config':
|
||||
specifier: workspace:*
|
||||
version: link:../configs/typescript
|
||||
'@types/crypto-js':
|
||||
specifier: ^4.2.2
|
||||
version: 4.2.2
|
||||
eslint:
|
||||
specifier: ^8.57.1
|
||||
version: 8.57.1
|
||||
typescript:
|
||||
specifier: 5.5.4
|
||||
version: 5.5.4
|
||||
|
||||
packages:
|
||||
|
||||
/@babel/code-frame@7.27.1:
|
||||
@@ -938,6 +969,10 @@ packages:
|
||||
'@babel/types': 7.28.5
|
||||
dev: true
|
||||
|
||||
/@types/crypto-js@4.2.2:
|
||||
resolution: {integrity: sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==}
|
||||
dev: true
|
||||
|
||||
/@types/estree@1.0.7:
|
||||
resolution: {integrity: sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==}
|
||||
|
||||
@@ -1222,10 +1257,18 @@ packages:
|
||||
shebang-command: 2.0.0
|
||||
which: 2.0.2
|
||||
|
||||
/crypto-js@4.2.0:
|
||||
resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==}
|
||||
dev: false
|
||||
|
||||
/csstype@3.2.3:
|
||||
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
|
||||
dev: true
|
||||
|
||||
/dayjs@1.11.19:
|
||||
resolution: {integrity: sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==}
|
||||
dev: false
|
||||
|
||||
/debug@4.4.0:
|
||||
resolution: {integrity: sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==}
|
||||
engines: {node: '>=6.0'}
|
||||
|
||||
Reference in New Issue
Block a user