-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathheader.tsx
543 lines (514 loc) · 22.1 KB
/
header.tsx
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
'use client'
import { BookOpen, ChevronDown, Download, Folder, ImageDown, LinkIcon, MessageSquareMore, Trash2, TriangleAlert } from 'lucide-react'
// import Link from 'next/link'
import { useEffect, useRef, useState } from 'react'
import Image from 'next/image'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@radix-ui/react-tooltip'
import { ExportImageDialog } from './export-dialog'
import { useToast } from '@/components/ui/use-toast'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Logo } from '@/components/logo'
import type { Content, ContentWithId, PreviewRef } from '@/types'
import type { ExportContent, ExportJSON } from '@/components/header/types'
import {
CACHE_KEY_TEMPLATE, CACHE_KEY_THEME,
addAllContents,
cn,
removeAllContents,
removeHtmlTags,
} from '@/lib'
import {
Menubar,
MenubarContent,
MenubarItem,
MenubarMenu,
MenubarSeparator,
MenubarShortcut,
// MenubarShortcut,
MenubarTrigger,
} from '@/components/ui/menubar'
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
// SelectLabel,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
DEFAULT_TEMPLATE,
DEFAULT_TEMPLATES,
DEFAULT_THEME,
DEFAULT_THEME_COLOR_MAP,
} from '@/theme'
import { usePlatform } from '@/hooks/use-platform'
interface HeaderProps {
contents: Content[];
setContents: (contents: ContentWithId[]) => void;
previewRef: React.RefObject<PreviewRef>;
templateName: string;
theme: string;
setTemplateName: (template: string) => void;
setTheme: (color: string) => void
setTableValue?: (tab: string) => void
}
type DialogType = 'save_file' | 'open_file' | 'reset_data' | 'user_guide'
export function Header(props: HeaderProps) {
const [isOpenFile, setIsOpenFile] = useState(false)
const [imageDialogOpen, setImageDialogOpen] = useState(false)
const [dialogType, setDialogType] = useState<DialogType>('save_file')
const [isExporting, setIsExporting] = useState(true)
const [scale, setScale] = useState('3')
const platform = usePlatform()
const { contents, setContents, previewRef, templateName, theme, setTemplateName, setTheme, setTableValue } = props
const { toast } = useToast()
const fileRef = useRef<HTMLInputElement>(null)
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if (e.key === 'o' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
if (!contents.length) {
handleOpenfileBtnClick()
} else {
handleDialogOpen('open_file')
}
}
if (e.key === 'e' && e.shiftKey && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
setImageDialogOpen(true)
setIsExporting(true)
setScale('1')
// open preview
setTableValue && setTableValue('preview')
}
if (e.key === 's' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
handleDialogOpen('save_file')
}
}
document.addEventListener('keydown', handleKeyDown)
return () => document.removeEventListener('keydown', handleKeyDown)
}, [contents.length, setTableValue])
// open different dialog by type
function handleDialogOpen(type: DialogType) {
setIsOpenFile(true)
setDialogType(type)
}
function handleOpenfileBtnClick() {
if (fileRef.current) {
fileRef.current.click()
setIsOpenFile(false)
}
}
// open from file
function handleFileImport(event: React.ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0]
if (file) {
// Check if it's a JSON file
const reader = new FileReader()
reader.onload = async (e) => {
const json = e.target?.result as string
try {
const importData = JSON.parse(json) as ExportJSON
if (typeof importData !== 'object' || importData === null) {
toast({
title: 'Empty JSON file',
description: 'Please upload a valid oneimg file.',
})
return
}
if (!(importData.type && importData.type === 'oneimg')) {
toast({
title: 'Invalid file format',
description: 'Please upload a valid oneimg file.',
})
return
}
if (importData.data && typeof importData.data === 'object') {
const exportContents = importData.data
const contents: ContentWithId[] = exportContents.map(item => item)
// remove previous all data
await removeAllContents()
// cache import data
await addAllContents(contents)
setContents(contents)
const templateName = (importData.theme ?? DEFAULT_TEMPLATE)
const theme = importData.themeColor ?? DEFAULT_THEME.label
setTemplateName(templateName)
setTheme(theme)
localStorage.setItem(CACHE_KEY_TEMPLATE, templateName)
localStorage.setItem(CACHE_KEY_THEME, theme)
// 允许前后两次选择相同文件
event.target.value = ''
}
} catch (error) {
toast({
title: 'Invalid file format',
description: 'Please upload a valid oneimg file.',
})
}
}
reader.readAsText(file)
}
}
// save as file
async function handleFileSave() {
const exportContents = await Promise.all(
contents.map((item) => {
return {
id: item.id,
title: item.title,
type: item.type,
content: item.content,
parentId: item.parentId,
uploadFiles: item.uploadFiles,
} as ExportContent
}),
)
const exportData: ExportJSON = {
type: 'oneimg',
version: 1,
source: 'https://oneimgai.com',
theme: templateName ?? DEFAULT_TEMPLATE,
themeColor: theme ?? DEFAULT_THEME.label,
data: exportContents,
}
// get theme content
const title = exportContents.find(item => item.type === 'theme_content')?.title
const date = new Date()
const fullDateString = `${date.toLocaleDateString().replace(/\//g, '-')}_${date.toLocaleTimeString().replaceAll(':', '')}`
const fileName = `${removeHtmlTags(title) || '未命名'}-${fullDateString}.oneimg`
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
try {
// open the system file save dialog
if (typeof window !== 'undefined' && 'showSaveFilePicker' in window) {
const handle = await (window as any).showSaveFilePicker({
suggestedName: fileName,
types: [{
description: 'OneImg File',
accept: { 'application/json': ['.oneimg'] },
}],
})
const writable = await handle.createWritable()
await writable.write(blob)
await writable.close()
toast({
title: '文件已保存',
duration: 1000,
})
} else {
// eslint-disable-next-line no-alert
const suggestedName = prompt('文件名称', fileName) || fileName
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = suggestedName
a.click()
URL.revokeObjectURL(a.href)
}
} catch (error) {
console.log('File save failed', error)
}
}
async function handleDataClear() {
await removeAllContents()
localStorage.clear()
setContents([])
setIsOpenFile(false)
setTemplateName(DEFAULT_TEMPLATE)
setTheme(DEFAULT_THEME.label)
}
// open the dialog of saving as image
async function handleImageExportDialogOpen() {
setImageDialogOpen(true)
setIsExporting(true)
setScale('3')
// open preview
setTableValue && setTableValue('preview')
}
return (
<TooltipProvider>
<header className="h-[58px] flex gap-4 items-center px-4 border-b border-b-gray-200">
{/* <Link href="/"> */}
{/* <Logo type="full" /> */}
{/* </Link> */}
<Input onChange={handleFileImport} type="file" accept=".oneimg" className="hidden" ref={fileRef} />
<Menubar className="p-0 cursor-pointer border-none bg-white hover:bg-accent">
<MenubarMenu>
<MenubarTrigger>
<Logo type="full" />
<ChevronDown className="ml-2 h-4 w-4" />
</MenubarTrigger>
<MenubarContent className="max-h-[calc(100vh-150px)] overflow-y-auto">
<MenubarItem onClick={() => {
if (!contents.length) {
handleOpenfileBtnClick()
} else {
handleDialogOpen('open_file')
}
}}>
<Folder className="w-4 h-4 mr-2" />
<span>打开文件</span>
{platform === 'mac' && <MenubarShortcut>⌘+O</MenubarShortcut>}
{platform === 'windows' && <MenubarShortcut>Ctrl+O</MenubarShortcut>}
</MenubarItem>
<MenubarItem onClick={() => handleDialogOpen('save_file')}>
<Download className="w-4 h-4 mr-2" />
<span>保存到...</span>
{platform === 'mac' && <MenubarShortcut>⌘+S</MenubarShortcut>}
{platform === 'windows' && <MenubarShortcut>Ctrl+S</MenubarShortcut>}
</MenubarItem>
<MenubarItem onClick={() => handleDialogOpen('reset_data')}>
<Trash2 className="w-4 h-4 mr-2" />
<span>重置项目</span>
</MenubarItem>
<MenubarItem onClick={handleImageExportDialogOpen}>
<ImageDown className="w-4 h-4 mr-2" />
<span>导出图片</span>
{platform === 'mac' && <MenubarShortcut>⌘+Shift+E</MenubarShortcut>}
{platform === 'windows' && <MenubarShortcut>Ctrl+Shift+E</MenubarShortcut>}
</MenubarItem>
<MenubarItem onClick={() => handleDialogOpen('user_guide')} >
<BookOpen className="w-4 h-4 mr-2" />
<span>指南</span>
</MenubarItem>
<MenubarItem asChild className="">
<a href="https://support.qq.com/product/673291" target="_blank" rel="noreferrer">
<MessageSquareMore className="w-4 h-4 mr-2" />
<span>反馈建议</span>
</a>
</MenubarItem>
<MenubarSeparator />
<MenubarItem asChild>
<a href="https://github.com/byodian/oneimg" target="_blank" rel="noreferrer">
<Image src="/images/github.svg" alt="github icon" className="w-4 h-4 mr-2" width={24} height={24} />
<span>Github</span>
</a>
</MenubarItem>
<Tooltip delayDuration={0}>
<TooltipTrigger className="w-full px-2 py-1.5 hidden sm:block">
<div className="flex items-center text-sm">
<Image src="/images/wechat.svg" alt="wechat icon" className="w-4 h-4 mr-2" width={24} height={24} />
<span>微信公众号</span>
</div>
</TooltipTrigger>
<TooltipContent side="right" sideOffset={-50}>
<div className="px-2 py-1.5 text-sm bg-white rounded-xl shadow-xl">
<Image src="/images/wechat.png" alt="github icon" width={500} height={500} />
</div>
</TooltipContent>
</Tooltip>
<MenubarItem asChild>
<a href="https://t.me/oneimg" target="_blank" rel="noreferrer">
<Image src="/images/telegram.svg" alt="telegram icon" className="w-4 h-4 mr-2" width={24} height={24} />
<span>TG 交流群</span>
</a>
</MenubarItem>
<MenubarItem asChild>
<a href="https://x.com/byodian1" target="_blank" rel="noreferrer">
<Image src="/images/x.svg" alt="x icon" className="w-4 h-4 mr-2" width={24} height={24} />
<span>Follow us</span>
</a>
</MenubarItem>
<MenubarItem asChild>
<a href="https://www.xiaohongshu.com/user/profile/61278fd2000000000100a607" target="_blank" rel="noreferrer">
<Image src="/images/xiaohongshu.svg" alt="xiaohongshu icon" className="w-4 h-4 mr-2" width={24} height={24} />
<span>小红书</span>
</a>
</MenubarItem>
<MenubarSeparator />
<div className="px-1.5 py-2 text-sm">
<div className="mb-2">模板</div>
<Select value={templateName} onValueChange={(value: string) => {
const themeColor = DEFAULT_THEME_COLOR_MAP[value][0].label
setTemplateName(value)
setTheme(themeColor)
localStorage.setItem(CACHE_KEY_TEMPLATE, value)
localStorage.setItem(CACHE_KEY_THEME, themeColor)
}}>
<SelectTrigger className="h-8">
<SelectValue className="text-muted-foreground" placeholder="请选择一个主题模版" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
{
DEFAULT_TEMPLATES.map(template => (
<SelectItem key={template.value} value={template.value} disabled={template.disabled}>
{template.label}
</SelectItem>
))
}
</SelectGroup>
</SelectContent >
</Select >
</div >
<div className="px-1.5 py-2 text-sm">
<div className="mb-2">模版色</div>
<div>
{DEFAULT_THEME_COLOR_MAP[templateName].map(color => (
<Button
key={color.value}
variant="ghost"
size="sm"
onClick={() => {
setTheme(color.label)
localStorage.setItem(CACHE_KEY_THEME, color.label)
}}
className={cn({ 'bg-accent': theme === color.label })}>
<div className="w-4 h-4 rounded-full" style={{ backgroundColor: color.value }}></div>
</Button>
))}
</div>
</div>
</MenubarContent >
</MenubarMenu >
</Menubar >
<div className="flex flex-wrap gap-2 ml-auto">
<Button size="sm" asChild variant="ghost" className="py-2 px-2">
<a href="https://github.com/byodian/oneimg" target="_blank" rel="noreferrer">
<Image src="/images/github.svg" alt="github icon" className="w-6 h-6" width={24} height={24} />
</a>
</Button>
<Button size="sm" onClick={handleImageExportDialogOpen}>
<ImageDown className="w-4 h-4 mr-2" />
<span>导出图片</span>
</Button>
</div>
<Dialog open={isOpenFile} onOpenChange={setIsOpenFile}>
{dialogType === 'open_file' && <DialogContent className="max-w-full sm:max-w-[900px] px-10 py-8 h-full overflow-y-auto sm:h-auto">
<DialogHeader>
<DialogTitle className="text-2xl mb-4">从文件加载</DialogTitle>
<DialogDescription className="hidden">
open file
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-8">
<div className="flex items-center gap-4 p-8 bg-gray-300 rounded-lg">
<div className="flex flex-grow-0 flex-shrink-0 items-center justify-center bg-yellow-400 w-[56px] h-[56px] rounded-full">
<TriangleAlert className="w-6 h-6" />
</div>
<div>
<p>从文件加载将<strong>替换您现有的内容</strong>。</p>
<p>您可以先使用下列方式备份您的数据</p>
</div>
<Button variant="default" className="ml-auto bg-yellow-400 text-black hover:bg-yellow-500" onClick={handleOpenfileBtnClick}>
从文件加载
</Button>
</div>
<div className="flex flex-col sm:flex-row justify-between gap-4">
<div className="text-center flex flex-col gap-4 px-6 py-4">
<h3 className="font-bold text-xl">保存到本地</h3>
<p className="text-sm flex-grow">将主题数据导出为文件,以便以后导入。</p>
<Button variant="outline" size="lg" onClick={handleFileSave}>保存到本地</Button>
</div>
<div className="text-center flex flex-col gap-4 px-6 py-4">
<h3 className="font-bold text-xl">导出为图片</h3>
<p className="text-sm flex-grow">将主题数据导出为图片</p>
<Button variant="outline" size="lg" onClick={handleImageExportDialogOpen}>导出为图片</Button>
</div>
<div className="text-center flex flex-col gap-4 px-6 py-4">
<h3 className="font-bold text-xl">OneIMG+</h3>
<p className="text-sm flex-grow">将主题数据保存到您的 OneIMG+ 工作区。</p>
<Button variant="outline" size="lg" disabled={true}>即将上线</Button>
</div>
</div>
</div>
</DialogContent>}
{dialogType === 'save_file' && <DialogContent className="max-w-full sm:max-w-[900px] px-10 py-8 h-full overflow-y-auto sm:h-auto">
<DialogHeader className="pb-4 border-b mb-4">
<DialogTitle className="text-2xl">保存到...</DialogTitle>
<DialogDescription className="hidden">
save as...
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-8">
<div className="flex flex-col sm:flex-row justify-between gap-4">
<div className="flex items-center justify-center flex-col gap-4 px-8 py-4">
<div className="flex flex-grow-0 flex-shrink-0 items-center justify-center bg-primary w-[110px] h-[110px] rounded-full">
<Download className="w-12 h-12 text-primary-foreground" />
</div>
<h3 className="font-bold text-xl">保存到本地</h3>
<p className="text-sm flex-grow">将主题数据导出为文件,以便以后导入。</p>
<Button
variant="outline"
size="lg"
onClick={async () => {
await handleFileSave()
setIsOpenFile(false)
}}>保存到本地</Button>
</div>
<div className="flex items-center justify-center flex-col gap-4 px-8 py-4">
<div className="flex flex-grow-0 flex-shrink-0 items-center justify-center bg-primary w-[110px] h-[110px] rounded-full">
<LinkIcon className="w-12 h-12 text-primary-foreground" />
</div>
<h3 className="font-bold text-xl">分享链接</h3>
<p className="text-sm flex-grow">导出为只读链接</p>
<Button variant="outline" size="lg" disabled={true}>即将上线</Button>
</div>
<div className="flex items-center justify-center flex-col gap-4 px-8 py-4">
<div className="flex flex-grow-0 flex-shrink-0 items-center justify-center bg-warning w-[110px] h-[110px] rounded-full">
<Logo type="part" className="w-12 h-12 text-warning-foreground" />
</div>
<h3 className="font-bold text-xl">OneIMG+</h3>
<p className="text-sm flex-grow">将主题数据保存到您的 OneIMG+ 工作区。</p>
<Button variant="outline" size="lg" disabled={true}>即将上线</Button>
</div>
</div>
</div>
</DialogContent>}
{dialogType === 'reset_data' && <DialogContent className="max-w-full sm:max-w-[495px] px-10 py-8 h-full overflow-y-auto sm:h-auto">
<DialogHeader className="text-2xl pb-4 border-b mb-4">
<DialogTitle className="">清除数据</DialogTitle>
<DialogDescription className="hidden">
reset all data
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-8 mb-8">
<p>
这将会清除整个主题数据。您是否继续?
</p>
</div>
<DialogFooter>
<div className="flex gap-4">
<Button variant="outline" onClick={() => setIsOpenFile(false)}>取消</Button>
<Button variant="destructive" onClick={handleDataClear}>确定</Button>
</div>
</DialogFooter>
</DialogContent>}
{dialogType === 'user_guide' && <DialogContent className="max-w-full sm:max-w-[900px] px-10 py-8 h-full overflow-y-auto sm:h-auto">
<DialogHeader className="text-2xl pb-4 border-b mb-4">
<DialogTitle className="">使用指南</DialogTitle>
<DialogDescription className="hidden">
User Guide
</DialogDescription>
</DialogHeader>
<div>
<video controls autoPlay muted width="100%" height="380px">
<source src="https://file.oneimgai.com/user-guide.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
</div>
</DialogContent>}
</Dialog>
<ExportImageDialog
previewRef={previewRef}
scale={scale}
setScale={setScale}
isExportModalOpen={imageDialogOpen}
setIsExportModalOpen={setImageDialogOpen}
isExporting={isExporting}
setIsExporting={setIsExporting}
/>
</header >
</TooltipProvider>
)
}