Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/auth/auth-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ authProvider.onDidChangeSessions(async e => {
await AuthManager.updateAuthStatus()
accountViewDataProvider.fireTreeDataChangedEvent()

postCategoryDataProvider.refresh()
await postCategoryDataProvider.refreshAsync()

if (e.removed != null) postDataProvider.refresh()
else await PostListView.refresh()
Expand Down
25 changes: 13 additions & 12 deletions src/cmd/pdf/post-pdf-template-builder.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/* eslint-disable prettier/prettier */
import { Post } from '@/model/post'
import { PostFileMapManager } from '@/service/post/post-file-map'
import fs from 'fs'
import { BlogSettingService } from '@/service/blog-setting'
import { PostCatService } from '@/service/post/post-cat'
import { PostCat } from '@/model/post-cat'
import { markdownItFactory } from '@cnblogs/markdown-it-presets'
import { UserService } from '@/service/user.service'
import { PostCateStore } from '@/stores/post-cate-store'

export namespace PostPdfTemplateBuilder {
export const HighlightedMessage = 'markdown-highlight-finished'
Expand All @@ -19,11 +20,11 @@ export namespace PostPdfTemplateBuilder {

const html = isMarkdown
? markdownItFactory({
codeHighlight: false,
math: true,
disableRules: [],
html: true,
}).render(postBody)
codeHighlight: false,
math: true,
disableRules: [],
html: true,
}).render(postBody)
: postBody

const buildTagHtml = (): Promise<string> => {
Expand All @@ -36,19 +37,19 @@ export namespace PostPdfTemplateBuilder {
}

const buildCategoryHtml = async (): Promise<string> => {
const categories = await PostCatService.getAll()
const categories = (await PostCateStore.createAsync()).getFlatAll()
const postCategories =
post.categoryIds
?.map(categoryId => categories.find(x => x.categoryId === categoryId))
.filter((x): x is PostCat => x != null) ?? []
let html =
postCategories.length > 0
? postCategories
.map(
c =>
`<a href="https://www.cnblogs.com/${blogApp}/category/${c.categoryId}.html" target="_blank">${c?.title}</a>`
)
.join(', ')
.map(
c =>
`<a href="https://www.cnblogs.com/${blogApp}/category/${c.categoryId}.html" target="_blank">${c?.title}</a>`
)
.join(', ')
: ''
html = html !== '' ? `<div id="BlogPostCat">分类: ${html}</div>` : ''
return html
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/post-cat/del-selected-cat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export async function delSelectedCat(input?: PostCatTreeItem | PostCat) {
}

p.report({ increment: 100 })
postCategoryDataProvider.refresh()
await postCategoryDataProvider.refreshAsync()
}
)
}
5 changes: 3 additions & 2 deletions src/cmd/post-cat/new-post-cat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { PostCatService } from '@/service/post/post-cat'
import { extTreeViews } from '@/tree-view/tree-view-register'
import { inputPostCat } from './input-post-cat'
import { postCategoryDataProvider } from '@/tree-view/provider/post-category-tree-data-provider'
import { PostCateStore } from '@/stores/post-cate-store'

export async function newPostCat() {
const input = await inputPostCat('新建分类')
Expand All @@ -22,9 +23,9 @@ export async function newPostCat() {
increment: 70,
})

postCategoryDataProvider.refresh()
await postCategoryDataProvider.refreshAsync()

const allCategory = await PostCatService.getAll()
const allCategory = (await PostCateStore.createAsync()).getFlatAll()
const newCategory = allCategory.find(x => x.title === input.title)
if (newCategory !== undefined) await extTreeViews.postCategoriesList.reveal(newCategory)

Expand Down
2 changes: 1 addition & 1 deletion src/cmd/post-cat/update-post-cat-treeview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export async function updatePostCatTreeView(arg?: PostCat | PostCatTreeItem) {
p.report({ increment: 10 })
try {
await PostCatService.update(updateDto)
postCategoryDataProvider.refresh()
await postCategoryDataProvider.refreshAsync()
p.report({ increment: 100 })
} catch (e) {
void Alert.err(`更新博文失败: ${<string>e}`)
Expand Down
10 changes: 5 additions & 5 deletions src/cmd/show-local-file-to-post-info.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
/* eslint-disable prettier/prettier */
import path from 'path'
import { Uri } from 'vscode'
import { Alert } from '@/infra/alert'
import { PostService } from '@/service/post/post'
import { PostCatService } from '@/service/post/post-cat'
import { PostFileMapManager } from '@/service/post/post-file-map'
import { searchPostByTitle } from '@/service/post/search-post-by-title'
import { viewPostOnline } from './view-post-online'
import format from 'date-fns/format'
import { PostCateStore } from '@/stores/post-cate-store'

/**
* 本地文件所关联的博文信息
Expand Down Expand Up @@ -64,7 +65,7 @@ export async function showLocalFileToPostInfo(input: Uri | number): Promise<numb

const { post } = await PostService.getPostEditDto(postId)

let categories = await PostCatService.getAll()
let categories = (await PostCateStore.createAsync()).getFlatAll()
categories = categories.filter(x => post.categoryIds?.includes(x.categoryId))
const categoryDesc = categories.length > 0 ? `博文分类: ${categories.map(c => c.title).join(', ')}\n` : ''
const tagsDesc = (post.tags?.length ?? 0) > 0 ? `博文标签: ${post.tags?.join(', ')}\n` : ''
Expand All @@ -77,9 +78,8 @@ export async function showLocalFileToPostInfo(input: Uri | number): Promise<numb
detail: `🔗博文链接: ${postUrl}\n博文发布时间: ${format(
post.datePublished ?? new Date(),
'yyyy-MM-dd HH:mm'
)}\n博文发布状态: ${post.isPublished ? '已发布' : '未发布'}\n博文访问权限: ${
post.accessPermissionDesc
}\n${categoryDesc}${tagsDesc}`.replace(/\n$/, ''),
)}\n博文发布状态: ${post.isPublished ? '已发布' : '未发布'}\n博文访问权限: ${post.accessPermissionDesc
}\n${categoryDesc}${tagsDesc}`.replace(/\n$/, ''),
},
...options
)
Expand Down
1 change: 0 additions & 1 deletion src/model/post-cat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ export class PostCat {
title = ''
visible = true
description = ''
updateTime: Date = new Date()
itemCount = 0
order?: number
childCount = 0
Expand Down
51 changes: 1 addition & 50 deletions src/service/post/post-cat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import { UserService } from '../user.service'
// TODO: need better cache impl
let siteCategoryCache: SiteCat[] | null = null

const DEFAULT_ORDER = 999999

async function getAuthedPostCatReq() {
const token = await AuthManager.acquireToken()
// TODO: need better solution
Expand All @@ -24,54 +22,7 @@ export namespace PostCatService {
const resp = await req.getAll()
const { categories } = <{ categories: PostCat[] }>JSON.parse(resp)
if (categories == null) return []
return categories.map(x => Object.assign(new PostCat(), x))
} catch (e) {
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
throw e
}
}

export async function getFlatAll() {
const categories = await getAll()
if (categories == null || categories.length === 0) return []

const flat = []
const queue = categories
while (queue.length > 0) {
const current = queue.pop()
if (current == null) continue
flat.push(current)
if (current.children != null) for (const child of current.children) queue.unshift(child)
}

return flat.sort((x, y) => {
const order1 = x.order ?? DEFAULT_ORDER
const order2 = y.order ?? DEFAULT_ORDER
if (order1 > order2) return 1
else if (order1 < order2) return -1
else return x.title.localeCompare(y.title)
})
}

export async function getOne(categoryId: number) {
const req = await getAuthedPostCatReq()
try {
const resp = await req.getOne(categoryId)
const { parent } = <{ parent: PostCat | null }>JSON.parse(resp)
return Object.assign(new PostCat(), parent)
} catch (e) {
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
throw e
}
}

export async function getAllUnder(parentId: number) {
const req = await getAuthedPostCatReq()
try {
const resp = await req.getOne(parentId)
const { categories } = <{ categories: PostCat[] }>JSON.parse(resp)
if (categories == null) return []
return categories.map(x => Object.assign(new PostCat(), x))
return categories
} catch (e) {
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
throw e
Expand Down
8 changes: 6 additions & 2 deletions src/service/post/post-cfg-panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { Token } from '@/wasm'
import { PostTagReq } from '@/wasm'
import { PostTag } from '@/wasm'
import { AuthManager } from '@/auth/auth-manager'
import { PostCateStore } from '@/stores/post-cate-store'

async function getAuthedPostTagReq() {
const token = await AuthManager.acquireToken()
Expand Down Expand Up @@ -72,11 +73,13 @@ export namespace PostCfgPanel {
baseUrl: webview.asWebviewUri(Uri.joinPath(globalCtx.assetsUri, 'fonts')).toString() + '/',
} as WebviewMsg.SetFluentIconBaseUrlMsg)

const postCateStore = await PostCateStore.createAsync()

await webview.postMessage({
command: Webview.Cmd.Ui.editPostCfg,
post: cloneDeep(post),
activeTheme: vscode.window.activeColorTheme.kind,
userCats: cloneDeep(await PostCatService.getFlatAll()),
userCats: cloneDeep(postCateStore.getFlatAll()),
siteCats: cloneDeep(await PostCatService.getSitePresetList()),
tags,
breadcrumbs,
Expand Down Expand Up @@ -161,10 +164,11 @@ const observeWebviewMsg = (panel: WebviewPanel, options: PostCfgPanelOpenOption)
await doUploadImg(webview, <WebviewMsg.UploadImgMsg>message)
} else if (command === Webview.Cmd.Ext.getChildCategories) {
const { payload } = message as WebviewCommonCmd<Webview.Cmd.GetChildCategoriesPayload>
const cateStore = await PostCateStore.createAsync()
await webview.postMessage({
command: Webview.Cmd.Ui.updateChildCategories,
payload: {
value: await PostCatService.getAllUnder(payload.parentId).catch(() => []),
value: cateStore.getChildren(payload.parentId),
parentId: payload.parentId,
},
})
Expand Down
2 changes: 1 addition & 1 deletion src/setup/setup-cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export function setupCmd() {
// post category
regCmd(extName`.post-category.new`, newPostCat),
regCmd(extName`.post-category.del-select`, delSelectedCat),
regCmd(extName`.post-category.refresh`, () => postCategoryDataProvider.refresh()),
regCmd(extName`.post-category.refresh`, () => postCategoryDataProvider.refreshAsync()),
regCmd(extName`.post-category.update`, updatePostCatTreeView),
// workspace
regCmd(extName`.workspace.set`, Workspace.set),
Expand Down
4 changes: 2 additions & 2 deletions src/setup/setup-watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import { PostListView } from '@/cmd/post-list/post-list-view'
import { postCategoryDataProvider } from '@/tree-view/provider/post-category-tree-data-provider'

export const setupCfgWatch = () =>
workspace.onDidChangeConfiguration(ev => {
workspace.onDidChangeConfiguration(async ev => {
if (ev.affectsConfiguration('cnblogsClient')) isTargetWorkspace()

if (ev.affectsConfiguration('workbench.iconTheme')) postCategoryDataProvider.refresh()
if (ev.affectsConfiguration('workbench.iconTheme')) await postCategoryDataProvider.refreshAsync()

if (ev.affectsConfiguration('cnblogsClient.pageSize.postList')) void PostListView.refresh({ queue: true })

Expand Down
95 changes: 95 additions & 0 deletions src/stores/post-cate-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { PostCat } from '@/model/post-cat'
import { PostCatService } from '@/service/post/post-cat'

const DEFAULT_ORDER: number = 999999

export class PostCateStore {
// eslint-disable-next-line prettier/prettier
constructor(private categories: ReadonlyArray<PostCat>) { }

get isNullOrEmpty() {
return this.categories == null || this.categories.length === 0
}

static async createAsync() {
const categories = await PostCatService.getAll()
return new PostCateStore(categories)
}

private static clonePostCat(categories: ReadonlyArray<PostCat>) {
return categories.map(x => {
const cate = Object.assign(new PostCat(), x)
return cate
})
}

async refreshAsync() {
this.categories = await PostCatService.getAll()
}

getFlatAll() {
if (this.isNullOrEmpty) return []

const flat: PostCat[] = []
const queue = this.getRoots()
while (queue.length > 0) {
const current = queue.pop()
if (current == null) continue
flat.push(Object.assign(new PostCat(), current))
if (current.children != null) for (const child of current.children) queue.unshift(child)
}

return flat.sort((x, y) => {
const order1 = x.order ?? DEFAULT_ORDER
const order2 = y.order ?? DEFAULT_ORDER
if (order1 > order2) return 1
else if (order1 < order2) return -1
else return x.title.localeCompare(y.title)
})
}

getRoots() {
if (this.isNullOrEmpty) return []
return PostCateStore.clonePostCat(this.categories)
}

getChildren(categoryId: number) {
if (this.isNullOrEmpty) return []

let children: PostCat[] = []
const queue = this.getRoots()
while (queue.length > 0) {
const current = queue.pop()
if (current == null) continue
if (current.categoryId === categoryId) {
if (current.children != null) children = current.children
break
}

if (current.children != null) for (const child of current.children) queue.unshift(child)
}

children = PostCateStore.clonePostCat(children)
return children
}

getOne(categoryId: number) {
if (this.isNullOrEmpty) return null

let category: PostCat | null = null
const queue = this.getRoots()
while (queue.length > 0) {
const current = queue.pop()
if (current == null) continue
if (current.categoryId === categoryId) {
category = Object.assign(new PostCat(), current)
break
}

if (current.children != null) for (const child of current.children) queue.unshift(child)
}

if (category != null) category.children = []
return category
}
}
Loading
Loading