Skip to content

Commit ea4fddd

Browse files
committed
refactor: introduce PostCateStore
1 parent 6862b3e commit ea4fddd

File tree

11 files changed

+132
-69
lines changed

11 files changed

+132
-69
lines changed

src/auth/auth-manager.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ authProvider.onDidChangeSessions(async e => {
1919
await AuthManager.updateAuthStatus()
2020
accountViewDataProvider.fireTreeDataChangedEvent()
2121

22-
postCategoryDataProvider.refresh()
22+
await postCategoryDataProvider.refreshAsync()
2323

2424
if (e.removed != null) postDataProvider.refresh()
2525
else await PostListView.refresh()

src/cmd/post-cat/del-selected-cat.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ export async function delSelectedCat(input?: PostCatTreeItem | PostCat) {
5656
}
5757

5858
p.report({ increment: 100 })
59-
postCategoryDataProvider.refresh()
59+
await postCategoryDataProvider.refreshAsync()
6060
}
6161
)
6262
}

src/cmd/post-cat/new-post-cat.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ export async function newPostCat() {
2222
increment: 70,
2323
})
2424

25-
postCategoryDataProvider.refresh()
25+
await postCategoryDataProvider.refreshAsync()
2626

2727
const allCategory = await PostCatService.getAll()
2828
const newCategory = allCategory.find(x => x.title === input.title)

src/cmd/post-cat/update-post-cat-treeview.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export async function updatePostCatTreeView(arg?: PostCat | PostCatTreeItem) {
3232
p.report({ increment: 10 })
3333
try {
3434
await PostCatService.update(updateDto)
35-
postCategoryDataProvider.refresh()
35+
await postCategoryDataProvider.refreshAsync()
3636
p.report({ increment: 100 })
3737
} catch (e) {
3838
void Alert.err(`更新博文失败: ${<string>e}`)

src/service/post/post-cat.ts

Lines changed: 0 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ import { UserService } from '../user.service'
88
// TODO: need better cache impl
99
let siteCategoryCache: SiteCat[] | null = null
1010

11-
const DEFAULT_ORDER = 999999
12-
1311
async function getAuthedPostCatReq() {
1412
const token = await AuthManager.acquireToken()
1513
// TODO: need better solution
@@ -31,53 +29,6 @@ export namespace PostCatService {
3129
}
3230
}
3331

34-
export async function getFlatAll() {
35-
const categories = await getAll()
36-
if (categories == null || categories.length === 0) return []
37-
38-
const flat = []
39-
const queue = categories
40-
while (queue.length > 0) {
41-
const current = queue.pop()
42-
if (current == null) continue
43-
flat.push(current)
44-
if (current.children != null) for (const child of current.children) queue.unshift(child)
45-
}
46-
47-
return flat.sort((x, y) => {
48-
const order1 = x.order ?? DEFAULT_ORDER
49-
const order2 = y.order ?? DEFAULT_ORDER
50-
if (order1 > order2) return 1
51-
else if (order1 < order2) return -1
52-
else return x.title.localeCompare(y.title)
53-
})
54-
}
55-
56-
export async function getOne(categoryId: number) {
57-
const req = await getAuthedPostCatReq()
58-
try {
59-
const resp = await req.getOne(categoryId)
60-
const { parent } = <{ parent: PostCat | null }>JSON.parse(resp)
61-
return Object.assign(new PostCat(), parent)
62-
} catch (e) {
63-
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
64-
throw e
65-
}
66-
}
67-
68-
export async function getAllUnder(parentId: number) {
69-
const req = await getAuthedPostCatReq()
70-
try {
71-
const resp = await req.getOne(parentId)
72-
const { categories } = <{ categories: PostCat[] }>JSON.parse(resp)
73-
if (categories == null) return []
74-
return categories.map(x => Object.assign(new PostCat(), x))
75-
} catch (e) {
76-
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
77-
throw e
78-
}
79-
}
80-
8132
export async function create(dto: PostCatAddDto) {
8233
const req = await getAuthedPostCatReq()
8334
const body = JSON.stringify(dto)

src/service/post/post-cfg-panel.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { Token } from '@/wasm'
1717
import { PostTagReq } from '@/wasm'
1818
import { PostTag } from '@/wasm'
1919
import { AuthManager } from '@/auth/auth-manager'
20+
import { PostCateStore } from '@/stores/post-cate-store'
2021

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

76+
const postCateStore = await PostCateStore.create()
77+
7578
await webview.postMessage({
7679
command: Webview.Cmd.Ui.editPostCfg,
7780
post: cloneDeep(post),
7881
activeTheme: vscode.window.activeColorTheme.kind,
79-
userCats: cloneDeep(await PostCatService.getFlatAll()),
82+
userCats: cloneDeep(postCateStore.getFlatAll()),
8083
siteCats: cloneDeep(await PostCatService.getSitePresetList()),
8184
tags,
8285
breadcrumbs,
@@ -161,10 +164,11 @@ const observeWebviewMsg = (panel: WebviewPanel, options: PostCfgPanelOpenOption)
161164
await doUploadImg(webview, <WebviewMsg.UploadImgMsg>message)
162165
} else if (command === Webview.Cmd.Ext.getChildCategories) {
163166
const { payload } = message as WebviewCommonCmd<Webview.Cmd.GetChildCategoriesPayload>
167+
const cateStore = await PostCateStore.create()
164168
await webview.postMessage({
165169
command: Webview.Cmd.Ui.updateChildCategories,
166170
payload: {
167-
value: await PostCatService.getAllUnder(payload.parentId).catch(() => []),
171+
value: cateStore.getChildren(payload.parentId),
168172
parentId: payload.parentId,
169173
},
170174
})

src/setup/setup-cmd.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ export function setupCmd() {
9292
// post category
9393
regCmd(extName`.post-category.new`, newPostCat),
9494
regCmd(extName`.post-category.del-select`, delSelectedCat),
95-
regCmd(extName`.post-category.refresh`, () => postCategoryDataProvider.refresh()),
95+
regCmd(extName`.post-category.refresh`, () => postCategoryDataProvider.refreshAsync()),
9696
regCmd(extName`.post-category.update`, updatePostCatTreeView),
9797
// workspace
9898
regCmd(extName`.workspace.set`, Workspace.set),

src/setup/setup-watch.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import { PostListView } from '@/cmd/post-list/post-list-view'
88
import { postCategoryDataProvider } from '@/tree-view/provider/post-category-tree-data-provider'
99

1010
export const setupCfgWatch = () =>
11-
workspace.onDidChangeConfiguration(ev => {
11+
workspace.onDidChangeConfiguration(async ev => {
1212
if (ev.affectsConfiguration('cnblogsClient')) isTargetWorkspace()
1313

14-
if (ev.affectsConfiguration('workbench.iconTheme')) postCategoryDataProvider.refresh()
14+
if (ev.affectsConfiguration('workbench.iconTheme')) await postCategoryDataProvider.refreshAsync()
1515

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

src/stores/post-cate-store.ts

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { PostCat } from '@/model/post-cat'
2+
import { PostCatService } from '@/service/post/post-cat'
3+
4+
const DEFAULT_ORDER: number = 999999
5+
6+
export class PostCateStore {
7+
// eslint-disable-next-line prettier/prettier
8+
constructor(private categories: PostCat[]) { }
9+
10+
get isNullOrEmpty() {
11+
return this.categories == null || this.categories.length === 0
12+
}
13+
14+
static async createAsync() {
15+
const categories = await PostCatService.getAll()
16+
return new PostCateStore(categories)
17+
}
18+
19+
private static clonePostCat(categories: PostCat[]) {
20+
return categories.map(x => {
21+
const cate = Object.assign(new PostCat(), x)
22+
cate.children = []
23+
return cate
24+
})
25+
}
26+
27+
async refreshAsync() {
28+
this.categories = await PostCatService.getAll()
29+
}
30+
31+
getFlatAll() {
32+
if (this.isNullOrEmpty) return []
33+
34+
const flat: PostCat[] = []
35+
const queue = this.categories
36+
while (queue.length > 0) {
37+
const current = queue.pop()
38+
if (current == null) continue
39+
flat.push(current)
40+
if (current.children != null) for (const child of current.children) queue.unshift(child)
41+
}
42+
43+
return flat.sort((x, y) => {
44+
const order1 = x.order ?? DEFAULT_ORDER
45+
const order2 = y.order ?? DEFAULT_ORDER
46+
if (order1 > order2) return 1
47+
else if (order1 < order2) return -1
48+
else return x.title.localeCompare(y.title)
49+
})
50+
}
51+
52+
getRoots() {
53+
if (this.isNullOrEmpty) return []
54+
return PostCateStore.clonePostCat(this.categories)
55+
}
56+
57+
getChildren(categoryId: number) {
58+
if (this.isNullOrEmpty) return []
59+
60+
let children: PostCat[] = []
61+
const queue = this.categories
62+
while (queue.length > 0) {
63+
const current = queue.pop()
64+
if (current == null) continue
65+
if (current.categoryId === categoryId) {
66+
children = current.children ?? []
67+
break
68+
}
69+
70+
if (current.children != null) for (const child of current.children) queue.unshift(child)
71+
}
72+
73+
children = PostCateStore.clonePostCat(children)
74+
console.log(JSON.stringify(children))
75+
return children
76+
}
77+
78+
getOne(categoryId: number) {
79+
if (this.isNullOrEmpty) return null
80+
81+
let category: PostCat | null = null
82+
const queue = this.categories
83+
while (queue.length > 0) {
84+
const current = queue.pop()
85+
if (current == null) continue
86+
if (current.categoryId === categoryId) {
87+
category = Object.assign(new PostCat(), current)
88+
break
89+
}
90+
91+
if (current.children != null) for (const child of current.children) queue.unshift(child)
92+
}
93+
94+
if (category != null) category.children = []
95+
return category
96+
}
97+
}

src/tree-view/model/post-metadata.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* eslint-disable prettier/prettier */
12
import differenceInSeconds from 'date-fns/differenceInSeconds'
23
import differenceInYears from 'date-fns/differenceInYears'
34
import format from 'date-fns/format'
@@ -6,12 +7,12 @@ import zhCN from 'date-fns/locale/zh-CN'
67
import { TreeItem, TreeItemCollapsibleState, ThemeIcon } from 'vscode'
78
import { AccessPermission, Post, formatAccessPermission } from '@/model/post'
89
import { PostEditDto } from '@/model/post-edit-dto'
9-
import { PostCatService } from '@/service/post/post-cat'
1010
import { PostService } from '@/service/post/post'
1111
import { BaseEntryTreeItem } from './base-entry-tree-item'
1212
import { BaseTreeItemSource } from './base-tree-item-source'
1313
import { PostTreeItem } from './post-tree-item'
1414
import { PostCat } from '@/model/post-cat'
15+
import { PostCateStore } from '@/stores/post-cate-store'
1516

1617
export enum RootPostMetadataType {
1718
categoryEntry = 'categoryEntry',
@@ -81,8 +82,8 @@ export abstract class PostMetadata extends BaseTreeItemSource {
8182

8283
export abstract class PostEntryMetadata<T extends PostMetadata = PostMetadata>
8384
extends PostMetadata
84-
implements BaseEntryTreeItem<T>
85-
{
85+
// eslint-disable-next-line prettier/prettier
86+
implements BaseEntryTreeItem<T> {
8687
constructor(
8788
parent: Post,
8889
public readonly children: T[]
@@ -138,8 +139,10 @@ export class PostCatMetadata extends PostMetadata {
138139
static async parse(parent: Post, editDto?: PostEditDto): Promise<PostCatMetadata[]> {
139140
if (editDto === undefined) editDto = await PostService.getPostEditDto(parent.id)
140141

142+
const cateStore = await PostCateStore.create()
143+
141144
const categoryIds = editDto.post.categoryIds ?? []
142-
const futList = categoryIds.map(PostCatService.getOne)
145+
const futList = categoryIds.map(x => cateStore.getOne(x))
143146
const categoryList = await Promise.all(futList)
144147

145148
return categoryList
@@ -214,8 +217,8 @@ export abstract class PostDateMetadata extends PostMetadata {
214217
toTreeItem = (): TreeItem =>
215218
Object.assign<TreeItem, TreeItem>(
216219
new TreeItem(
217-
`${this.label}: ${
218-
this.shouldUseDistance() ? this.distance + `(${this.formattedDate})` : this.formattedDate
220+
// eslint-disable-next-line prettier/prettier
221+
`${this.label}: ${this.shouldUseDistance() ? this.distance + `(${this.formattedDate})` : this.formattedDate
219222
}`
220223
),
221224
{
@@ -267,7 +270,7 @@ export class PostAccessPermissionMetadata extends PostMetadata {
267270
Object.assign<TreeItem, Partial<TreeItem>>(
268271
new TreeItem(
269272
`访问权限: ${formatAccessPermission(this.parent.accessPermission)}` +
270-
(isPasswordRequired ? '(需密码)' : '')
273+
(isPasswordRequired ? '(需密码)' : '')
271274
),
272275
{
273276
iconPath: PostAccessPermissionMetadata.parseIcon(this.parent.accessPermission, isPasswordRequired),

0 commit comments

Comments
 (0)