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:
Firman Ramdhani
2026-01-09 16:50:25 +07:00
parent 7a6a8b710f
commit ed949e4174
19 changed files with 1238 additions and 3 deletions
+1
View File
@@ -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",
+5
View File
@@ -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>
+279
View File
@@ -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 &lt; 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 &gt; Application &gt; LocalStorage</em>. Cari key{' '}
<code>my_secure_token</code>. Kamu akan melihat string acak (encrypted), bukan teks asli.
</p>
</div>
</div>
</div>
</div>
</div>
);
};
+4 -2
View File
@@ -1,2 +1,4 @@
export * from "./header";
export * from "./counter";
export * from './header';
export * from './counter';
export * from './date-example';
export * from './encryption-demo';