-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
452 lines (405 loc) · 17.4 KB
/
App.tsx
File metadata and controls
452 lines (405 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import React, { useState, useEffect, useRef } from 'react';
import {
Hash,
Binary,
Type,
Calculator,
History,
Save,
Trash2,
Eraser,
AlertCircle,
PenLine,
Cpu,
Download,
Upload
} from 'lucide-react';
import { isValidHex, hexToDecimal, hexToBinary, hexToAscii } from './utils/hexUtils';
import { useHistory } from './hooks/useHistory';
import { TEMPLATES_STORAGE_KEY } from './hooks/useBitTemplates';
import { ConversionResult, HistoryItem } from './types';
import { HistoryCard } from './components/HistoryCard';
import { CopyButton } from './components/CopyButton';
import { ByteAnalyzerModal } from './components/ByteAnalyzerModal';
import { ExportModal } from './components/ExportModal';
import { Toast, ToastProps } from './components/Toast';
const App: React.FC = () => {
// Use lazy initialization for persistence to ensure we read before write
const [hexInput, setHexInput] = useState(() => localStorage.getItem('s-hex-current-input') || '');
const [noteInput, setNoteInput] = useState(() => localStorage.getItem('s-hex-current-note') || '');
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<Omit<ConversionResult, 'timestamp'> | null>(null);
// Analyzer State
const [isAnalyzerOpen, setIsAnalyzerOpen] = useState(false);
const [analyzerInitialData, setAnalyzerInitialData] = useState<{hex: string, labels: string[], note: string} | null>(null);
// Export/UI State
const [exportItem, setExportItem] = useState<HistoryItem | null>(null);
const [toast, setToast] = useState<Omit<ToastProps, 'onClose'> | null>(null);
const { history, addToHistory, clearHistory, deleteItem, importHistory } = useHistory();
const fileInputRef = useRef<HTMLInputElement>(null);
// Persistence effects
useEffect(() => {
localStorage.setItem('s-hex-current-input', hexInput);
}, [hexInput]);
useEffect(() => {
localStorage.setItem('s-hex-current-note', noteInput);
}, [noteInput]);
// Handle Real-time conversion
useEffect(() => {
if (!hexInput) {
setResult(null);
setError(null);
return;
}
const cleanInput = hexInput.replace(/\s+/g, '');
if (!cleanInput) {
setResult(null);
setError(null);
return;
}
if (!isValidHex(cleanInput)) {
setError('请输入有效的16进制字符 (0-9, A-F)');
setResult(null);
return;
}
setError(null);
setResult({
hex: cleanInput,
decimal: hexToDecimal(cleanInput),
binary: hexToBinary(cleanInput),
ascii: hexToAscii(cleanInput),
});
}, [hexInput]);
const handleSave = () => {
if (result) {
addToHistory({
...result,
timestamp: Date.now()
}, noteInput);
setNoteInput('');
setToast({ message: '结果已保存', type: 'success' });
}
};
const handleSaveAnalyzer = (analysisResult: ConversionResult, bitLabels: string[], note: string) => {
const itemToSave = {
...analysisResult,
bitLabels: bitLabels
};
addToHistory(itemToSave as any, note || "字节位分析");
setToast({ message: '分析结果已保存', type: 'success' });
};
const restoreHistoryItem = (item: HistoryItem) => {
if (item.bitLabels) {
setAnalyzerInitialData({
hex: item.hex,
labels: item.bitLabels,
note: item.note || ''
});
setIsAnalyzerOpen(true);
} else {
setHexInput(item.hex);
window.scrollTo({ top: 0, behavior: 'smooth' });
}
};
const closeAnalyzer = () => {
setIsAnalyzerOpen(false);
setAnalyzerInitialData(null);
};
const openNewAnalyzer = () => {
setAnalyzerInitialData(null);
setIsAnalyzerOpen(true);
};
// --- Import / Export Logic ---
const handleExportData = () => {
try {
const templates = JSON.parse(localStorage.getItem(TEMPLATES_STORAGE_KEY) || '[]');
const data = {
version: 1,
exportedAt: Date.now(),
history,
templates
};
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `S-Hex-Data-${new Date().toISOString().split('T')[0]}.json`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
setToast({ message: '数据已成功导出', type: 'success' });
} catch (e) {
console.error("Export failed", e);
setToast({ message: '导出失败', type: 'error' });
}
};
const handleImportClick = () => {
fileInputRef.current?.click();
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
try {
const content = event.target?.result as string;
const data = JSON.parse(content);
let historyImported = 0;
let templatesImported = 0;
// Import History
if (data.history && Array.isArray(data.history)) {
importHistory(data.history);
historyImported = data.history.length;
}
// Import Templates
if (data.templates && Array.isArray(data.templates)) {
const currentTemplates = JSON.parse(localStorage.getItem(TEMPLATES_STORAGE_KEY) || '[]');
const existingIds = new Set(currentTemplates.map((t: any) => t.id));
const newTemplates = data.templates.filter((t: any) => !existingIds.has(t.id));
if (newTemplates.length > 0) {
const combinedTemplates = [...newTemplates, ...currentTemplates];
localStorage.setItem(TEMPLATES_STORAGE_KEY, JSON.stringify(combinedTemplates));
templatesImported = newTemplates.length;
// Dispatch storage event so other hooks (like ByteAnalyzer) see the change
window.dispatchEvent(new StorageEvent('storage', {
key: TEMPLATES_STORAGE_KEY,
newValue: JSON.stringify(combinedTemplates)
}));
}
}
setToast({
message: `数据导入成功!\n- 历史记录: ${historyImported} 条\n- 位定义模板: ${templatesImported} 个`,
type: 'success'
});
} catch (err) {
console.error(err);
setToast({ message: '导入失败:文件格式不正确或已损坏', type: 'error' });
}
};
reader.readAsText(file);
e.target.value = '';
};
return (
<div className="min-h-screen bg-slate-50 text-slate-900 font-sans selection:bg-brand-100 selection:text-brand-700">
{/* Header */}
<header className="bg-white border-b border-slate-200 sticky top-0 z-10 bg-opacity-80 backdrop-blur-md">
<div className="max-w-6xl mx-auto px-4 h-16 flex items-center justify-between">
<div className="flex items-center space-x-2">
<div className="w-8 h-8 bg-brand-600 rounded-lg flex items-center justify-center text-white shadow-brand-500/20 shadow-lg">
<Hash size={20} strokeWidth={2.5} />
</div>
<h1 className="text-xl font-bold tracking-tight text-slate-800">S - Hex</h1>
</div>
<div className="flex items-center space-x-2">
<input
type="file"
ref={fileInputRef}
onChange={handleFileChange}
accept=".json"
className="hidden"
/>
<button
onClick={handleImportClick}
className="flex items-center space-x-1.5 px-3 py-1.5 bg-white border border-slate-200 hover:bg-slate-50 text-slate-600 rounded-md text-sm font-medium transition-colors"
title="导入数据 (包含历史和模板)"
>
<Upload size={16} />
<span className="hidden sm:inline">导入数据</span>
</button>
<button
onClick={handleExportData}
className="flex items-center space-x-1.5 px-3 py-1.5 bg-white border border-slate-200 hover:bg-slate-50 text-slate-600 rounded-md text-sm font-medium transition-colors"
title="导出全部数据 (包含历史记录和自定义模板)"
>
<Download size={16} />
<span className="hidden sm:inline">导出备份</span>
</button>
<div className="h-6 w-px bg-slate-200 mx-1"></div>
<button
onClick={openNewAnalyzer}
className="flex items-center space-x-1.5 px-3 py-1.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-md text-sm font-medium transition-colors"
>
<Cpu size={16} />
<span className="hidden sm:inline">字节分析</span>
</button>
</div>
</div>
</header>
<main className="max-w-6xl mx-auto px-4 py-8 grid grid-cols-1 lg:grid-cols-12 gap-8">
{/* Left Column: Converter */}
<div className="lg:col-span-7 flex flex-col space-y-6">
<section className="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
<div className="flex justify-between items-center mb-4">
<label htmlFor="hexInput" className="text-sm font-semibold text-slate-600 uppercase tracking-wider flex items-center gap-2">
<Hash size={16} className="text-brand-500" />
输入 16 进制 (Hex)
</label>
<button
onClick={() => {
setHexInput('');
setNoteInput('');
}}
className="text-slate-400 hover:text-slate-600 text-sm flex items-center gap-1 transition-colors"
disabled={!hexInput}
>
<Eraser size={14} /> 清空
</button>
</div>
<div className="relative">
<textarea
id="hexInput"
value={hexInput}
onChange={(e) => setHexInput(e.target.value.replace(/[^0-9a-fA-F\s]/g, ''))}
className={`w-full h-32 text-xl font-mono p-4 rounded-xl border-2 bg-slate-50 focus:bg-white transition-all outline-none resize-none
${error ? 'border-red-300 focus:border-red-500 text-red-600' : 'border-slate-100 focus:border-brand-500 text-slate-800'}
placeholder:text-slate-300
`}
placeholder="在此输入十六进制代码,例如: 48 65 6c 6c 6f..."
spellCheck={false}
/>
{error && (
<div className="absolute bottom-4 right-4 flex items-center text-red-500 text-sm font-medium animate-pulse">
<AlertCircle size={16} className="mr-1" />
{error}
</div>
)}
</div>
<div className="mt-4 flex flex-col sm:flex-row items-end sm:items-center justify-end gap-3">
<div className="relative w-full sm:w-64">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-slate-400">
<PenLine size={16} />
</div>
<input
type="text"
value={noteInput}
onChange={(e) => setNoteInput(e.target.value)}
placeholder="添加备注(可选)"
disabled={!result || !!error}
className="w-full pl-9 pr-4 py-2.5 rounded-lg border border-slate-200 bg-slate-50 focus:bg-white focus:border-brand-500 focus:ring-1 focus:ring-brand-500 outline-none text-sm transition-all disabled:opacity-50"
/>
</div>
<button
onClick={handleSave}
disabled={!result || !!error}
className={`
flex items-center space-x-2 px-6 py-2.5 rounded-lg font-medium transition-all whitespace-nowrap w-full sm:w-auto justify-center
${!result || !!error
? 'bg-slate-100 text-slate-400 cursor-not-allowed'
: 'bg-brand-600 text-white hover:bg-brand-700 shadow-md hover:shadow-lg active:scale-95'}
`}
>
<Save size={18} />
<span>保存结果</span>
</button>
</div>
</section>
{result && !error ? (
<div className="space-y-4 animate-in fade-in slide-in-from-bottom-4 duration-500">
<div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
<div className="bg-slate-50 px-6 py-3 border-b border-slate-100 flex justify-between items-center">
<div className="flex items-center space-x-2 text-slate-600 font-medium">
<Calculator size={18} className="text-indigo-500" />
<span>十进制 (Decimal)</span>
</div>
<CopyButton text={result.decimal} />
</div>
<div className="p-6 font-mono text-lg break-all text-slate-800">
{result.decimal}
</div>
</div>
<div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
<div className="bg-slate-50 px-6 py-3 border-b border-slate-100 flex justify-between items-center">
<div className="flex items-center space-x-2 text-slate-600 font-medium">
<Type size={18} className="text-emerald-500" />
<span>ASCII 字符</span>
</div>
<CopyButton text={result.ascii} />
</div>
<div className="p-6 font-mono text-lg break-all text-slate-800 whitespace-pre-wrap min-h-[5rem]">
{result.ascii || <span className="text-slate-300 italic">无法转换或结果为空</span>}
</div>
</div>
<div className="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
<div className="bg-slate-50 px-6 py-3 border-b border-slate-100 flex justify-between items-center">
<div className="flex items-center space-x-2 text-slate-600 font-medium">
<Binary size={18} className="text-pink-500" />
<span>二进制 (Binary)</span>
</div>
<CopyButton text={result.binary} />
</div>
<div className="p-6 font-mono text-sm break-all text-slate-600 leading-relaxed max-h-60 overflow-y-auto custom-scrollbar">
{result.binary}
</div>
</div>
</div>
) : (
<div className="h-64 flex flex-col items-center justify-center text-slate-300 border-2 border-dashed border-slate-200 rounded-2xl">
<Calculator size={48} className="mb-4 opacity-50" />
<p>输入16进制数据以查看转换结果</p>
</div>
)}
</div>
{/* Right Column: History */}
<div className="lg:col-span-5">
<div className="sticky top-24">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-bold text-slate-800 flex items-center gap-2">
<History size={20} className="text-slate-500" />
历史记录
</h2>
{history.length > 0 && (
<button
onClick={clearHistory}
className="text-xs text-red-500 hover:text-red-700 bg-red-50 hover:bg-red-100 px-3 py-1.5 rounded-full transition-colors flex items-center gap-1"
>
<Trash2 size={12} /> 清除全部
</button>
)}
</div>
<div className="bg-slate-100 rounded-2xl p-4 min-h-[500px] max-h-[calc(100vh-140px)] overflow-y-auto custom-scrollbar shadow-inner">
{history.length === 0 ? (
<div className="h-full flex flex-col items-center justify-center text-slate-400 space-y-3 py-20">
<div className="w-16 h-16 bg-slate-200 rounded-full flex items-center justify-center">
<History size={24} className="opacity-50" />
</div>
<p className="text-sm">暂无历史记录</p>
</div>
) : (
<div className="space-y-3">
{history.map((item) => (
<HistoryCard
key={item.id}
item={item}
onDelete={deleteItem}
onRestore={restoreHistoryItem}
onExport={setExportItem}
/>
))}
</div>
)}
</div>
</div>
</div>
</main>
<ByteAnalyzerModal
isOpen={isAnalyzerOpen}
onClose={closeAnalyzer}
onSave={handleSaveAnalyzer}
initialData={analyzerInitialData}
/>
<ExportModal
item={exportItem}
onClose={() => setExportItem(null)}
/>
{toast && (
<Toast
message={toast.message}
type={toast.type}
onClose={() => setToast(null)}
/>
)}
</div>
);
};
export default App;