forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShareDialog.vue
More file actions
557 lines (500 loc) · 19 KB
/
Copy pathShareDialog.vue
File metadata and controls
557 lines (500 loc) · 19 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
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
<script setup lang="ts">
import type { Component } from 'vue'
import type { ShareListItem, SharePasswordMode } from '@/services/share/types'
import { Check, Clock, Copy, ExternalLink, Eye, Globe, KeyRound, Loader2, LogIn, RefreshCw, Share2, Sparkles, Trash2 } from '@lucide/vue'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { captureShareSnapshot } from '@/services/share/capture-snapshot'
import { isShareConfigured, ShareApiError, ShareClient } from '@/services/share/client'
import { useAuthStore } from '@/stores/auth'
import { useConfirmStore } from '@/stores/confirm'
import { usePostStore } from '@/stores/post'
import { useUIStore } from '@/stores/ui'
const props = defineProps<{
open: boolean
}>()
const emit = defineEmits([`update:open`])
interface PasswordOption {
value: SharePasswordMode
label: string
description: string
icon: Component
}
const passwordOptions: PasswordOption[] = [
{
value: `none`,
label: `公开链接`,
description: `任何人持链接即可查看`,
icon: Globe,
},
{
value: `custom`,
label: `自定义密码`,
description: `自行设置 4–64 位访问密码`,
icon: KeyRound,
},
{
value: `auto`,
label: `随机密码`,
description: `系统生成 8 位密码,生成后展示`,
icon: Sparkles,
},
]
const authStore = useAuthStore()
const postStore = usePostStore()
const uiStore = useUIStore()
const confirmStore = useConfirmStore()
const { isLoggedIn, user } = storeToRefs(authStore)
const activeTab = ref<`create` | `manage`>(`create`)
const shareList = ref<ShareListItem[]>([])
const isLoadingList = ref(false)
const revokingId = ref<string | null>(null)
const isProUser = computed(() => {
if (!user.value || user.value.plan !== `pro`)
return false
return user.value.planExpiresAt != null && user.value.planExpiresAt > Date.now()
})
const dialogVisible = computed({
get: () => props.open,
set: value => emit(`update:open`, value),
})
const shareClient = new ShareClient(() => authStore.token)
const passwordMode = ref<SharePasswordMode>(`none`)
const customPassword = ref(``)
const isSubmitting = ref(false)
const submitStage = ref(``)
const shareUrl = ref(``)
const sharePassword = ref(``)
const isProtected = ref(false)
const expiresAt = ref<number | null>(null)
const errorMessage = ref(``)
const copiedLink = ref(false)
const copiedPassword = ref(false)
const expiresLabel = computed(() => {
if (!expiresAt.value)
return ``
return new Date(expiresAt.value).toLocaleString(`zh-CN`)
})
const canSubmit = computed(() => {
if (passwordMode.value === `custom`)
return customPassword.value.trim().length >= 4
return true
})
function resetForm() {
passwordMode.value = `none`
customPassword.value = ``
shareUrl.value = ``
sharePassword.value = ``
isProtected.value = false
expiresAt.value = null
errorMessage.value = ``
copiedLink.value = false
copiedPassword.value = false
}
function resetDialog() {
activeTab.value = `create`
resetForm()
}
function formatShareTitle(title: string): string {
const trimmed = title.trim()
return trimmed || `无标题`
}
function formatShareExpiry(expiresAt: number | null, expired: boolean): string {
if (expired)
return `已过期`
if (!expiresAt)
return `永久有效`
return `${new Date(expiresAt).toLocaleString(`zh-CN`)} 过期`
}
async function loadShareList() {
if (!isLoggedIn.value)
return
isLoadingList.value = true
try {
const result = await shareClient.list()
shareList.value = result.shares
}
catch (err) {
const message = err instanceof ShareApiError && err.message === `pro_required`
? `我的分享为 Pro 专属功能`
: err instanceof Error ? err.message : String(err)
toast.error(`加载分享列表失败:${message}`)
}
finally {
isLoadingList.value = false
}
}
function confirmRevokeShare(share: ShareListItem) {
confirmStore.confirm({
title: `取消分享`,
description: `确定取消「${formatShareTitle(share.title)}」的分享吗?链接将立即失效。`,
confirmText: `取消分享`,
destructive: true,
onConfirm: async () => {
revokingId.value = share.id
try {
await shareClient.revoke(share.id)
shareList.value = shareList.value.filter(item => item.id !== share.id)
if (shareUrl.value === share.url)
resetForm()
toast.success(`已取消分享`)
}
catch (err) {
const message = err instanceof Error ? err.message : String(err)
toast.error(`取消分享失败:${message}`)
}
finally {
revokingId.value = null
}
},
})
}
function openAccountDialog() {
dialogVisible.value = false
uiStore.toggleShowAccountDialog(true)
}
function formatShareError(err: unknown): string {
if (err instanceof ShareApiError && err.status === 429 && err.body?.error === `rate_limited`) {
const limit = typeof err.body.limit === `number` ? err.body.limit : null
const retryAfterSec = typeof err.body.retryAfterSec === `number` ? err.body.retryAfterSec : null
const limitText = limit != null ? `每天最多分享 ${limit} 次` : `分享过于频繁`
const retryHint = retryAfterSec != null
? retryAfterSec >= 3600
? `,请 ${Math.ceil(retryAfterSec / 3600)} 小时后再试`
: `,请 ${Math.max(1, Math.ceil(retryAfterSec / 60))} 分钟后再试`
: `,请明天再试`
return `${limitText}${retryHint}`
}
if (err instanceof Error)
return err.message
return String(err)
}
async function createShare() {
if (isSubmitting.value || !isLoggedIn.value || !canSubmit.value)
return
isSubmitting.value = true
submitStage.value = `正在等待图表与公式渲染…`
errorMessage.value = ``
shareUrl.value = ``
sharePassword.value = ``
isProtected.value = false
copiedLink.value = false
copiedPassword.value = false
try {
const htmlSnapshot = await captureShareSnapshot()
submitStage.value = `正在上传分享快照…`
const currentPost = postStore.currentPost
if (!currentPost?.id)
throw new Error(`当前文章无效,请刷新后重试。`)
const result = await shareClient.create({
postId: currentPost.id,
title: currentPost.title ?? ``,
htmlSnapshot,
passwordMode: passwordMode.value,
...(passwordMode.value === `custom` ? { password: customPassword.value.trim() } : {}),
})
shareUrl.value = result.url
expiresAt.value = result.expiresAt
isProtected.value = result.protected
sharePassword.value = result.password ?? ``
toast.success(result.updated ? `分享链接已更新` : `分享链接已生成`)
}
catch (err) {
const message = formatShareError(err)
errorMessage.value = message === `invalid_password`
? `密码长度需为 4–64 个字符。`
: message === `forbidden`
? `无权更新此分享,请刷新后重试。`
: message
toast.error(`生成分享链接失败:${errorMessage.value}`)
}
finally {
isSubmitting.value = false
submitStage.value = ``
}
}
async function copyText(text: string, kind: `link` | `password`) {
if (!text)
return
try {
await navigator.clipboard.writeText(text)
if (kind === `link`) {
copiedLink.value = true
window.setTimeout(() => {
copiedLink.value = false
}, 2000)
}
else {
copiedPassword.value = true
window.setTimeout(() => {
copiedPassword.value = false
}, 2000)
}
toast.success(`已复制`)
}
catch {
toast.error(`复制失败,请手动复制`)
}
}
async function copyShareBundle() {
if (!shareUrl.value)
return
const lines = [`链接:${shareUrl.value}`]
if (sharePassword.value)
lines.push(`密码:${sharePassword.value}`)
await copyText(lines.join(`\n`), `link`)
}
function openSharePage() {
if (shareUrl.value)
openShareUrl(shareUrl.value)
}
function openShareUrl(url: string) {
window.open(url, `_blank`, `noopener,noreferrer`)
}
watch(() => props.open, (visible) => {
if (visible)
resetDialog()
})
watch(activeTab, (tab) => {
if (tab === `manage` && props.open && isProUser.value)
loadShareList()
})
watch(isProUser, (pro) => {
if (!pro && activeTab.value === `manage`)
activeTab.value = `create`
})
</script>
<template>
<Dialog v-model:open="dialogVisible">
<DialogContent class="gap-0 p-0 sm:max-w-md">
<DialogHeader class="space-y-1.5 border-b px-6 py-4">
<DialogTitle class="flex items-center gap-2">
<Share2 class="size-5" />
分享预览
</DialogTitle>
<DialogDescription>
生成与编辑器预览一致的只读链接,便于转发给他人查看。
</DialogDescription>
</DialogHeader>
<div v-if="!isShareConfigured()" class="px-6 py-8 text-center text-sm text-muted-foreground">
分享服务未配置,请联系部署方启用。
</div>
<div v-else-if="!isLoggedIn" class="flex flex-col items-center gap-4 px-6 py-8">
<p class="text-sm text-muted-foreground">
请先登录账户后再分享
</p>
<Button class="gap-2" @click="openAccountDialog">
<LogIn class="size-4" />
前往登录
</Button>
</div>
<Tabs v-else v-model="activeTab" class="gap-0">
<TabsList v-if="isProUser" class="mx-6 mt-4 grid w-auto grid-cols-2">
<TabsTrigger value="create">
生成分享
</TabsTrigger>
<TabsTrigger value="manage">
我的分享
</TabsTrigger>
</TabsList>
<TabsContent value="create" class="mt-0">
<template v-if="!shareUrl">
<div class="space-y-4 px-6 py-4">
<div class="flex flex-wrap gap-2">
<span class="inline-flex items-center gap-1 rounded-md border bg-background px-2 py-1 text-xs text-muted-foreground">
<Clock class="size-3.5" />
1 天后过期
</span>
<span
v-if="!isProUser"
class="inline-flex items-center gap-1 rounded-md border bg-background px-2 py-1 text-xs text-muted-foreground"
>
2 次/天
</span>
</div>
<div class="space-y-2">
<Label class="text-sm">访问密码</Label>
<div class="grid gap-2">
<button
v-for="option in passwordOptions"
:key="option.value"
type="button"
class="flex w-full items-start gap-3 rounded-lg border px-3 py-2.5 text-left transition-colors"
:class="passwordMode === option.value
? 'border-primary bg-primary/5 ring-1 ring-primary/20'
: 'hover:bg-muted/50'"
@click="passwordMode = option.value"
>
<component :is="option.icon" class="mt-0.5 size-4 shrink-0 text-muted-foreground" />
<span class="min-w-0 flex-1">
<span class="block text-sm font-medium">{{ option.label }}</span>
<span class="block text-xs text-muted-foreground">{{ option.description }}</span>
</span>
<span
class="mt-1 size-2 shrink-0 rounded-full"
:class="passwordMode === option.value ? 'bg-primary' : 'bg-muted-foreground/30'"
/>
</button>
</div>
</div>
<div v-if="passwordMode === 'custom'" class="space-y-2 pl-1">
<Label for="share-custom-password" class="text-xs text-muted-foreground">
输入访问密码
</Label>
<Input
id="share-custom-password"
v-model="customPassword"
type="password"
autocomplete="new-password"
placeholder="4–64 个字符"
/>
</div>
<Alert v-if="errorMessage" variant="destructive" class="py-2.5">
<AlertDescription class="text-xs">
{{ errorMessage }}
</AlertDescription>
</Alert>
</div>
<div class="border-t px-6 py-4">
<Button class="w-full gap-2" :disabled="isSubmitting || !canSubmit" @click="createShare">
<Loader2 v-if="isSubmitting" class="size-4 animate-spin" />
<Share2 v-else class="size-4" />
{{ isSubmitting ? (submitStage || '正在生成…') : '生成分享链接' }}
</Button>
</div>
</template>
<template v-else>
<div class="space-y-4 px-6 py-4">
<Alert class="border-green-200 bg-green-50 py-2.5 text-green-900 dark:border-green-900/40 dark:bg-green-950/30 dark:text-green-100">
<AlertDescription class="text-xs">
分享链接已就绪,可直接复制或打开预览。
</AlertDescription>
</Alert>
<div class="space-y-2">
<Label for="share-url" class="text-xs text-muted-foreground">分享链接</Label>
<div class="flex gap-2">
<Input
id="share-url"
:model-value="shareUrl"
readonly
class="font-mono text-xs"
/>
<Button variant="outline" size="icon" @click="copyText(shareUrl, 'link')">
<Check v-if="copiedLink" class="size-4 text-green-600" />
<Copy v-else class="size-4" />
</Button>
<Button variant="outline" size="icon" @click="openSharePage">
<ExternalLink class="size-4" />
</Button>
</div>
</div>
<div v-if="isProtected && sharePassword" class="space-y-2">
<Label for="share-password" class="text-xs text-muted-foreground">访问密码</Label>
<div class="flex gap-2">
<Input
id="share-password"
:model-value="sharePassword"
readonly
class="font-mono text-xs"
/>
<Button variant="outline" size="icon" @click="copyText(sharePassword, 'password')">
<Check v-if="copiedPassword" class="size-4 text-green-600" />
<Copy v-else class="size-4" />
</Button>
</div>
<Button variant="outline" class="w-full" @click="copyShareBundle">
复制链接与密码
</Button>
</div>
<p v-else-if="isProtected && passwordMode === 'custom'" class="text-xs text-muted-foreground">
已启用密码保护,请妥善保管你设置的密码。
</p>
<div class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
<span v-if="expiresLabel">过期:{{ expiresLabel }}</span>
<span>预览与编辑器一致</span>
</div>
</div>
<div class="border-t px-6 py-4">
<Button variant="outline" class="w-full" @click="resetForm">
重新设置并生成
</Button>
</div>
</template>
</TabsContent>
<TabsContent v-if="isProUser" value="manage" class="mt-0">
<div class="space-y-3 px-6 py-4">
<div class="flex items-center justify-between gap-2">
<p class="text-xs text-muted-foreground">
管理已发布的分享链接,取消后链接立即失效。
</p>
<Button
variant="ghost"
size="icon"
class="shrink-0"
title="刷新列表"
:disabled="isLoadingList"
@click="loadShareList"
>
<Loader2 v-if="isLoadingList" class="size-4 animate-spin" />
<RefreshCw v-else class="size-4" />
</Button>
</div>
<div v-if="isLoadingList && shareList.length === 0" class="flex items-center justify-center py-10 text-sm text-muted-foreground">
<Loader2 class="mr-2 size-4 animate-spin" />
加载中…
</div>
<div v-else-if="shareList.length === 0" class="rounded-lg border border-dashed px-4 py-10 text-center text-sm text-muted-foreground">
暂无分享记录
</div>
<div v-else class="max-h-80 space-y-2 overflow-y-auto pr-1">
<div
v-for="share in shareList"
:key="share.id"
class="rounded-lg border p-3"
:class="share.expired ? 'opacity-70' : ''"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0 flex-1">
<p class="truncate text-sm font-medium">
{{ formatShareTitle(share.title) }}
</p>
<div class="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground">
<span class="inline-flex items-center gap-1">
<Eye class="size-3" />
{{ share.viewCount }} 次阅读
</span>
<span>{{ formatShareExpiry(share.expiresAt, share.expired) }}</span>
<span v-if="share.protected">已设密码</span>
</div>
</div>
<div class="flex shrink-0 items-center gap-1">
<Button variant="ghost" size="icon" title="复制链接" @click="copyText(share.url, 'link')">
<Copy class="size-4" />
</Button>
<Button variant="ghost" size="icon" title="打开预览" @click="openShareUrl(share.url)">
<ExternalLink class="size-4" />
</Button>
<Button
variant="ghost"
size="icon"
class="text-destructive hover:text-destructive"
title="取消分享"
:disabled="revokingId === share.id"
@click="confirmRevokeShare(share)"
>
<Loader2 v-if="revokingId === share.id" class="size-4 animate-spin" />
<Trash2 v-else class="size-4" />
</Button>
</div>
</div>
</div>
</div>
</div>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
</template>