forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostInfo.vue
More file actions
489 lines (448 loc) · 18.3 KB
/
Copy pathPostInfo.vue
File metadata and controls
489 lines (448 loc) · 18.3 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
<script setup lang="ts">
import type { Post, PostAccount } from '@md/shared/types'
import { Check, ChevronDown, ChevronRight, Info, Loader2, Minus, Send } from '@lucide/vue'
import { CheckboxIndicator, CheckboxRoot, Primitive } from 'reka-ui'
import { useEditorStore } from '@/stores/editor'
import { useRenderStore } from '@/stores/render'
import { useUIStore } from '@/stores/ui'
defineOptions({
inheritAttrs: false,
})
const editorStore = useEditorStore()
const { editor } = storeToRefs(editorStore)
const renderStore = useRenderStore()
const { output } = storeToRefs(renderStore)
const uiStore = useUIStore()
const { isMobile } = storeToRefs(uiStore)
const dialogVisible = ref(false)
const thumbPreviewVisible = ref(false)
const extensionInstalled = ref(false)
const allAccounts = ref<PostAccount[]>([])
const postTaskDialogVisible = ref(false)
const isCheckingLogin = ref(false)
const form = ref<Post>({
title: ``,
desc: ``,
thumb: ``,
content: ``,
markdown: ``,
accounts: [] as PostAccount[],
})
const allowPost = computed(() => extensionInstalled.value && allAccounts.value.some(a => a.checked && a.loggedIn))
// 平台分类配置
const platformCategories = [
{
name: `媒体平台`,
platforms: [`wechat`, `toutiao`, `zhihu`, `baijiahao`, `wangyihao`, `sohu`, `weibo`, `bilibili`, `sspai`, `twitter`, `douyin`, `xiaohongshu`, `douban`],
},
{
name: `博客平台`,
platforms: [`csdn`, `cnblogs`, `juejin`, `medium`, `cto51`, `segmentfault`, `oschina`, `infoq`, `jianshu`],
},
{
name: `云平台及开发者社区`,
platforms: [`tencentcloud`, `aliyun`, `huaweicloud`, `huaweidev`, `qianfan`, `alipayopen`, `modelscope`, `volcengine`, `elecfans`],
},
]
// 分类折叠状态(默认折叠云平台及开发者社区)
const collapsedCategories = ref<Set<string>>(new Set([`云平台及开发者社区`]))
function toggleCategory(categoryName: string) {
if (collapsedCategories.value.has(categoryName)) {
collapsedCategories.value.delete(categoryName)
}
else {
collapsedCategories.value.add(categoryName)
}
}
// 按分类获取账号
const accountsByCategory = computed(() => {
return platformCategories.map(category => ({
name: category.name,
accounts: category.platforms
.map(type => allAccounts.value.find(a => a.type === type))
.filter((a): a is PostAccount => a !== undefined),
}))
})
// 判断分类是否全选(只考虑已登录的账号)
function isCategoryAllSelected(accounts: PostAccount[]) {
const loggedInAccounts = accounts.filter(a => a.loggedIn)
return loggedInAccounts.length > 0 && loggedInAccounts.every(a => a.checked)
}
// 判断分类是否部分选中
function isCategoryIndeterminate(accounts: PostAccount[]) {
const loggedInAccounts = accounts.filter(a => a.loggedIn)
const checkedCount = loggedInAccounts.filter(a => a.checked).length
return checkedCount > 0 && checkedCount < loggedInAccounts.length
}
// 切换分类全选
function toggleCategorySelectAll(accounts: PostAccount[]) {
const loggedInAccounts = accounts.filter(a => a.loggedIn)
const allSelected = loggedInAccounts.every(a => a.checked)
loggedInAccounts.forEach(a => a.checked = !allSelected)
}
async function prePost() {
// 如果扩展已安装且还没有账号数据,则开始检测
if (extensionInstalled.value && allAccounts.value.length === 0) {
// 不 await,让检测在后台进行
startLoginDetection()
}
let auto: Post = {
thumb: ``,
title: ``,
desc: ``,
content: ``,
markdown: ``,
accounts: [],
}
const accounts = allAccounts.value.filter(a => ![`ipfs`].includes(a.type))
try {
auto = {
thumb: document.querySelector<HTMLImageElement>(`#output img`)?.src ?? ``,
title: [1, 2, 3, 4, 5, 6]
.map(h => document.querySelector(`#output h${h}`))
.find(h => h)
?.textContent ?? ``,
desc: document.querySelector(`#output p`)?.textContent?.trim() ?? ``,
content: output.value,
markdown: editor.value?.state.doc.toString() ?? ``,
accounts,
}
}
catch {
// 静默失败
}
finally {
form.value = {
...auto,
}
}
}
// 监听对话框打开,自动加载数据
watch(dialogVisible, (newVal) => {
if (newVal) {
prePost()
}
})
declare global {
interface Window {
syncPost: (data: { thumb: string, title: string, desc: string, content: string }) => void
$cose: any
}
}
// 获取初始平台列表(不带登录状态,用于立即显示)
function getInitialPlatforms(): PostAccount[] {
if (window.$cose !== undefined && typeof window.$cose.getPlatforms === 'function') {
return window.$cose.getPlatforms().map((p: any) => ({
...p,
checked: false,
loggedIn: false,
isChecking: true, // 标记正在检测中
}))
}
return []
}
// 开始登录检测(异步,不阻塞 UI,渐进式更新)
function startLoginDetection() {
if (window.$cose === undefined)
return
// 立即显示平台列表(带检测中状态)
const initialPlatforms = getInitialPlatforms()
if (initialPlatforms.length > 0) {
allAccounts.value = initialPlatforms
}
isCheckingLogin.value = true
let hasReceivedAny = false
// 设置超时机制:如果 15 秒内没有任何响应,则停止检测
const LOGIN_CHECK_TIMEOUT_MS = 15000
const timeoutId = setTimeout(() => {
if (!hasReceivedAny) {
allAccounts.value = allAccounts.value.map(a => ({ ...a, isChecking: false }))
isCheckingLogin.value = false
}
}, LOGIN_CHECK_TIMEOUT_MS)
// 检查是否支持渐进式 API
if (typeof window.$cose.getAccountsProgressive === 'function') {
// 使用渐进式 API:每个平台检测完成后立即更新 UI
window.$cose.getAccountsProgressive(
// onProgress: 每个平台完成时调用
(account: PostAccount, _completed: number, _total: number) => {
hasReceivedAny = true
// 更新对应平台的状态
const idx = allAccounts.value.findIndex(a => a.type === account.type)
if (idx !== -1) {
allAccounts.value[idx] = { ...account, checked: false, isChecking: false }
}
},
// onComplete: 所有平台完成时调用
() => {
clearTimeout(timeoutId)
isCheckingLogin.value = false
},
)
}
else {
// 回退到原有 API
window.$cose.getAccounts((resp: PostAccount[]) => {
hasReceivedAny = true
clearTimeout(timeoutId)
allAccounts.value = resp.map(a => ({ ...a, checked: false, isChecking: false }))
isCheckingLogin.value = false
})
}
}
// 兼容旧的 getAccounts 调用(checkExtension 使用)
async function getAccounts(): Promise<void> {
return new Promise((resolve) => {
startLoginDetection()
// 立即 resolve,不等待检测完成
resolve()
})
}
function post() {
// 从 allAccounts 获取用户选择的平台(checkbox 绑定在 allAccounts 上)
form.value.accounts = allAccounts.value.filter(a => a.checked && a.loggedIn)
postTaskDialogVisible.value = true
dialogVisible.value = false
}
function onUpdate(val: boolean) {
if (!val) {
dialogVisible.value = false
}
}
function getPlatformUrl(type: string): string {
const urls: Record<string, string> = {
csdn: 'https://blog.csdn.net',
juejin: 'https://juejin.cn',
wechat: 'https://mp.weixin.qq.com',
zhihu: 'https://www.zhihu.com/signin',
toutiao: 'https://mp.toutiao.com',
segmentfault: 'https://segmentfault.com/user/login',
cnblogs: 'https://i.cnblogs.com/articles/edit',
oschina: 'https://my.oschina.net/blog/write',
cto51: 'https://blog.51cto.com/blogger/publish?&newBloger=2',
infoq: 'https://xie.infoq.cn/draft/',
jianshu: 'https://www.jianshu.com/sign_in',
baijiahao: 'https://baijiahao.baidu.com',
wangyihao: 'https://mp.163.com/subscribe_v4/index.html#/article-publish',
tencentcloud: 'https://cloud.tencent.com/developer',
medium: 'https://medium.com/m/signin',
sspai: 'https://sspai.com/write',
sohu: 'https://mp.sohu.com/mpfe/v4/login',
bilibili: 'https://passport.bilibili.com/login',
weibo: 'https://passport.weibo.com/sso/signin',
aliyun: 'https://account.aliyun.com/login/login.htm',
huaweicloud: 'https://bbs.huaweicloud.com/blogs/article',
huaweidev: 'https://developer.huawei.com/consumer/cn/blog/create',
twitter: 'https://x.com/compose/articles/edit/',
qianfan: 'https://qianfan.cloud.baidu.com/qianfandev/topic/create',
alipayopen: 'https://open.alipay.com/portal/forum/post/add#article',
modelscope: 'https://modelscope.cn/learn/create',
volcengine: 'https://developer.volcengine.com/articles/draft',
douyin: 'https://creator.douyin.com/creator-micro/content/post/article?default-tab=5&enter_from=publish_page&media_type=article&type=new',
xiaohongshu: 'https://creator.xiaohongshu.com/publish/publish?from=menu&target=article',
elecfans: 'https://www.elecfans.com/d/article/md/',
douban: 'https://www.douban.com/note/create',
}
return urls[type] || '#'
}
function onAvatarError(account: PostAccount, event: Event) {
const img = event.target as HTMLImageElement
if (!account)
return
img.style.display = 'none'
}
function checkExtension() {
if (window.$cose !== undefined) {
extensionInstalled.value = true
getAccounts() // 立即开始登录检测
return
}
// 如果插件还没加载,5秒内每 500ms 检查一次
const EXTENSION_CHECK_INTERVAL_MS = 500
const MAX_EXTENSION_CHECKS = 10
let count = 0
const timer = setInterval(async () => {
if (window.$cose !== undefined) {
extensionInstalled.value = true
await getAccounts()
clearInterval(timer)
return
}
count++
if (count > MAX_EXTENSION_CHECKS) {
clearInterval(timer)
}
}, EXTENSION_CHECK_INTERVAL_MS)
}
onBeforeMount(() => {
checkExtension()
})
</script>
<template>
<div v-bind="$attrs">
<Dialog v-model:open="dialogVisible" @update:open="onUpdate">
<DialogTrigger>
<Button v-if="!isMobile" variant="outline" class="h-9">
<Send class="mr-2 h-4 w-4" />
发布
</Button>
</DialogTrigger>
<DialogContent class="!w-[750px] !max-w-[95vw] max-h-[85vh] flex flex-col overflow-hidden">
<DialogHeader>
<DialogTitle>发布</DialogTitle>
<DialogDescription>
将文章发布到多个平台
</DialogDescription>
</DialogHeader>
<div class="flex-1 overflow-y-auto p-1 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden flex flex-col gap-4">
<Alert v-if="!extensionInstalled">
<Info class="h-4 w-4" />
<AlertTitle>未检测到插件</AlertTitle>
<AlertDescription>
请安装 <a href="https://chromewebstore.google.com/detail/ilhikcdphhpjofhlnbojifbihhfmmhfk" target="_blank" rel="noopener noreferrer" class="underline text-primary">COSE 文章同步助手</a> 浏览器扩展
</AlertDescription>
</Alert>
<Alert>
<Info class="h-4 w-4" />
<AlertDescription>
此功能由 <a href="https://github.com/doocs/cose" target="_blank" rel="noopener noreferrer" class="underline"> GitHub 开源插件 COSE</a> 支持,完全本地运行,不收集、不存储任何用户信息。<br>如需添加更多平台或改善同步准确度,欢迎提 <a href="https://github.com/doocs/cose/issues" target="_blank" rel="noopener noreferrer" class="underline">Issue</a> 或 PR。
</AlertDescription>
</Alert>
<div class="w-full flex flex-col gap-4" :class="{ 'pointer-events-none opacity-50': !extensionInstalled }" :inert="!extensionInstalled || undefined" :aria-disabled="!extensionInstalled">
<div class="w-full flex items-center gap-4">
<Label for="thumb" class="w-10 text-end">
封面
</Label>
<div class="flex-1 flex items-center gap-2">
<Input id="thumb" v-model="form.thumb" placeholder="自动提取第一张图" class="flex-1" />
<Button v-if="form.thumb" variant="outline" size="sm" class="shrink-0" @click="thumbPreviewVisible = true">
查看
</Button>
</div>
</div>
<div class="w-full flex items-center gap-4">
<Label for="title" class="w-10 text-end">
标题
</Label>
<Input id="title" v-model="form.title" placeholder="自动提取第一个标题" />
</div>
<div class="w-full flex items-start gap-4">
<Label for="desc" class="w-10 text-end">
描述
</Label>
<Textarea id="desc" v-model="form.desc" placeholder="自动提取第一个段落" />
</div>
<div class="w-full flex items-start gap-4">
<Label class="w-10 text-end">
平台
</Label>
<div class="flex-1 space-y-3">
<div v-for="category in accountsByCategory" :key="category.name">
<div class="flex items-center gap-2 mb-2">
<div
class="flex items-center gap-1 cursor-pointer select-none text-sm font-medium text-muted-foreground hover:text-foreground"
@click="toggleCategory(category.name)"
>
<ChevronDown v-if="!collapsedCategories.has(category.name)" class="h-4 w-4" />
<ChevronRight v-else class="h-4 w-4" />
<span>{{ category.name }}</span>
<span class="text-xs">({{ category.accounts.length }})</span>
</div>
<div class="flex items-center gap-1 ml-2">
<CheckboxRoot
:model-value="isCategoryAllSelected(category.accounts) ? true : isCategoryIndeterminate(category.accounts) ? 'indeterminate' : false"
class="bg-background hover:bg-muted h-[18px] w-[18px] flex shrink-0 appearance-none items-center justify-center border border-gray-300 rounded-[3px] outline-hidden"
@click.stop="toggleCategorySelectAll(category.accounts)"
>
<CheckboxIndicator>
<Check v-if="isCategoryAllSelected(category.accounts)" class="h-3 w-3" />
<Minus v-else-if="isCategoryIndeterminate(category.accounts)" class="h-3 w-3" />
</CheckboxIndicator>
</CheckboxRoot>
<span class="text-xs text-muted-foreground">全选</span>
</div>
</div>
<div v-show="!collapsedCategories.has(category.name)" class="grid grid-cols-2 gap-x-8 gap-y-2 pl-5">
<div
v-for="account in category.accounts"
:key="account.uid"
class="flex items-center gap-2 whitespace-nowrap"
>
<CheckboxRoot
v-model="account.checked"
:disabled="!account.loggedIn"
class="bg-background hover:bg-muted h-[18px] w-[18px] flex shrink-0 appearance-none items-center justify-center border border-gray-300 rounded-[3px] outline-hidden disabled:opacity-50 disabled:cursor-not-allowed"
>
<CheckboxIndicator>
<Check v-if="account.checked" class="h-3 w-3" />
</CheckboxIndicator>
</CheckboxRoot>
<img
:src="account.icon"
alt=""
class="inline-block h-[16px] w-[16px] shrink-0"
>
<span class="text-sm font-medium">{{ account.title }}</span>
<!-- 检测中:显示转圈动画 -->
<template v-if="account.isChecking">
<Loader2 class="ml-1 h-3.5 w-3.5 animate-spin text-muted-foreground" />
<span class="text-xs text-muted-foreground">检测中</span>
</template>
<!-- 已登录:显示头像和用户名 -->
<template v-else-if="account.loggedIn">
<img
v-if="account.avatar"
:src="account.avatar"
alt=""
class="ml-1 h-4 w-4 rounded-full object-cover"
@error="onAvatarError(account, $event)"
>
<span class="text-sm text-muted-foreground">@{{ account.displayName }}</span>
</template>
<!-- 未登录:显示登录链接 -->
<Primitive
v-else
as="a"
:href="getPlatformUrl(account.type)"
target="_blank"
rel="noopener noreferrer"
class="ml-1 text-sm text-muted-foreground hover:underline"
>
登录
</Primitive>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" @click="dialogVisible = false">
取 消
</Button>
<Button :disabled="!allowPost" @click="post">
确 定
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog v-model:open="thumbPreviewVisible">
<DialogContent class="!max-w-[80vw] !w-fit">
<DialogHeader>
<DialogTitle>封面预览</DialogTitle>
</DialogHeader>
<div class="flex items-center justify-center p-2">
<img
:src="form.thumb"
alt="封面预览"
class="max-h-[70vh] max-w-full rounded-md object-contain"
@load="($event.target as HTMLImageElement).style.removeProperty('display')"
@error="($event.target as HTMLImageElement).style.display = 'none'"
>
</div>
</DialogContent>
</Dialog>
<PostTaskDialog v-model:open="postTaskDialogVisible" :post="form" />
</div>
</template>