Skip to content

Commit

Permalink
refactor: create post ux (#180)
Browse files Browse the repository at this point in the history
  • Loading branch information
Thaumy authored Aug 22, 2023
1 parent 5f15dc1 commit 1dfe1a4
Show file tree
Hide file tree
Showing 106 changed files with 1,107 additions and 1,611 deletions.
9 changes: 9 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@
"endOfLine": "auto",
"semi": false
}
],
"@typescript-eslint/strict-boolean-expressions": [
"error",
{
"allowString": false,
"allowNumber": false,
"allowNullableObject": false,
"allowNullableBoolean": false
}
]
},
"ignorePatterns": [
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@
"enablement": "vscode-cnb.isAuthed"
},
{
"command": "vscode-cnb.post.create-local",
"command": "vscode-cnb.post.create",
"title": "新建博文",
"icon": "$(new-file)",
"category": "Cnblogs Local Draft"
Expand Down Expand Up @@ -855,7 +855,7 @@
"group": "navigation@6"
},
{
"command": "vscode-cnb.post.create-local",
"command": "vscode-cnb.post.create",
"when": "view == cnblogs-post-list || view == cnblogs-post-list-another",
"group": "navigation@7"
},
Expand Down Expand Up @@ -1059,7 +1059,7 @@
"when": "viewItem =~ /^cnb-post/ && viewItem != cnb-post-category"
},
{
"command": "vscode-cnb.post.create-local",
"command": "vscode-cnb.post.create",
"when": "viewItem == cnb-local-posts-folder"
},
{
Expand Down
1 change: 1 addition & 0 deletions rs/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,5 @@ serde-wasm-bindgen = "0.5.0"
serde_with = "3.1.0"

reqwest = { version = "0.11.16", features = ["json"] }

lazy_static = "1.4.0"
14 changes: 13 additions & 1 deletion rs/src/cnb/ing/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
mod comment;
mod get_comment;
mod get_list;
mod r#pub;
mod publish;

use crate::panic_hook;
use alloc::string::{String, ToString};
use lazy_static::lazy_static;
use regex::Regex;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(js_name = IngReq)]
Expand All @@ -24,3 +26,13 @@ impl IngReq {
}
}
}

#[wasm_bindgen(js_name = ingStarIconToText)]
pub fn ing_star_tag_to_text(icon: &str) -> String {
lazy_static! {
static ref REGEX: Regex = Regex::new(r#"<img.*alt="\[(.*?)]".*>"#).unwrap();
}
let caps = REGEX.captures(icon).unwrap();
let star_text = caps.get(1).unwrap().as_str();
star_text.to_string()
}
4 changes: 2 additions & 2 deletions rs/src/cnb/ing/pub.rs → rs/src/cnb/ing/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ use wasm_bindgen::prelude::*;

#[wasm_bindgen(js_class = IngReq)]
impl IngReq {
#[wasm_bindgen(js_name = pub)]
pub async fn export_pub(&self, content: &str, is_private: bool) -> Result<(), String> {
#[wasm_bindgen(js_name = publish)]
pub async fn export_publish(&self, content: &str, is_private: bool) -> Result<(), String> {
panic_hook!();
let url = openapi!("/statuses");

Expand Down
4 changes: 2 additions & 2 deletions src/auth/auth-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ authProvider.onDidChangeSessions(async ({ added }) => {
await AuthManager.updateAuthStatus()

accountViewDataProvider.fireTreeDataChangedEvent()
postDataProvider.fireTreeDataChangedEvent(undefined)
postDataProvider.fireTreeDataChangedEvent()
postCategoryDataProvider.fireTreeDataChangedEvent()

BlogExportProvider.optionalInstance?.refreshRecords({ force: false, clearCache: true }).catch(console.warn)
await BlogExportProvider.optionalInstance?.refreshRecords({ force: false, clearCache: true })
})

export namespace AuthManager {
Expand Down
3 changes: 2 additions & 1 deletion src/auth/auth-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export class AuthSession implements CodeAuthSession {

const accessTokenPart2 = this.accessToken.split('.')[1]
const buf = Buffer.from(accessTokenPart2, 'base64')
return (<{ exp: number }>JSON.parse(buf.toString())).exp
const exp = <number>JSON.parse(buf.toString()).exp
return exp * 1000 < Date.now()
}
}
16 changes: 5 additions & 11 deletions src/cmd/blog-export/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,13 @@ export async function deleteBlogExport(input: unknown): Promise<void> {
function confirm(
itemName: string,
hasLocalFile = true,
detail: string | undefined | null = '数据可能无法恢复, 请谨慎操作!'
detail: string
): Thenable<null | { shouldDeleteLocal: boolean } | undefined> {
const options = [
{ title: '确定' + (hasLocalFile ? '(保留本地文件)' : ''), result: { shouldDeleteLocal: false } },
...(hasLocalFile ? [{ title: '确定(同时删除本地文件)', result: { shouldDeleteLocal: true } }] : []),
]
return Alert.info(
`确定要删除 ${itemName} 吗?`,
{ modal: true, detail: detail ? detail : undefined },
...options
).then(
return Alert.info(`确定要删除 ${itemName} 吗?`, { modal: true, detail }, ...options).then(
x => x?.result,
() => undefined
)
Expand Down Expand Up @@ -66,14 +62,12 @@ async function deleteExportRecordItem(item: BlogExportRecordTreeItem) {
void Alert.err(`删除博客备份失败: ${<string>e}`)
return false
})
if (hasDeleted) if (downloaded) await removeDownloadedBlogExport(downloaded, { shouldDeleteLocal })
if (hasDeleted) if (downloaded !== undefined) await removeDownloadedBlogExport(downloaded, { shouldDeleteLocal })

await BlogExportProvider.optionalInstance?.refreshRecords()
}

async function removeDownloadedBlogExport(downloaded: DownloadedBlogExport, { shouldDeleteLocal = false }) {
await DownloadedExportStore.remove(downloaded, { shouldRemoveExportRecordMap: shouldDeleteLocal }).catch(
console.warn
)
if (shouldDeleteLocal) await promisify(fs.rm)(downloaded.filePath).catch(console.warn)
await DownloadedExportStore.remove(downloaded, { shouldRemoveExportRecordMap: shouldDeleteLocal })
if (shouldDeleteLocal) await promisify(fs.rm)(downloaded.filePath)
}
34 changes: 14 additions & 20 deletions src/cmd/blog-export/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import path from 'path'
import { promisify } from 'util'
import { execCmd } from '@/infra/cmd'
import { WorkspaceCfg } from '@/ctx/cfg/workspace'
import AdmZip from 'adm-zip'

function parseInput(input: unknown): BlogExportRecordTreeItem | null | undefined {
return input instanceof BlogExportRecordTreeItem ? input : null
Expand All @@ -37,8 +38,8 @@ export async function downloadBlogExport(input: unknown) {
const { optionalInstance: blogExportProvider } = BlogExportProvider
await setIsDownloading(true)

const onError = (msg?: string | null) => {
if (msg) void Alert.warn(msg)
const onError = (msg: string) => {
void Alert.warn(msg)
if (!isFileExist) fs.rmSync(zipFilePath)
blogExportProvider?.refreshItem(treeItem)
setIsDownloading(false).then(undefined, console.warn)
Expand Down Expand Up @@ -70,26 +71,19 @@ export async function downloadBlogExport(input: unknown) {
treeItem.reportDownloadingProgress({ percentage: 100, message: '解压中' })
blogExportProvider?.refreshItem(treeItem)

import('adm-zip')
// eslint-disable-next-line @typescript-eslint/naming-convention
.then(({ default: AdmZip }) => {
void (async () => {
try {
const entry = new AdmZip(zipFilePath)
return promisify(entry.extractAllToAsync.bind(entry))(
targetDir,
true,
undefined
).then(() => promisify(fs.rm)(zipFilePath))
})
.then(() => {
DownloadedExportStore.add(nonZipFilePath, exportId)
.then(() => treeItem.reportDownloadingProgress(null))
.then(() => blogExportProvider?.refreshItem(treeItem))
.then(() => blogExportProvider?.refreshDownloadedExports())
.catch(console.warn)
}, console.warn)
.finally(() => {
await promisify(entry.extractAllToAsync.bind(entry))(targetDir, true, undefined)
await promisify(fs.rm)(zipFilePath)
await DownloadedExportStore.add(nonZipFilePath, exportId)
treeItem.reportDownloadingProgress(null)
blogExportProvider?.refreshItem(treeItem)
await blogExportProvider?.refreshDownloadedExports()
} finally {
setIsDownloading(false).then(undefined, console.warn)
})
}
})()
})
)
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/blog-export/edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function parseInput(input: unknown): ExportPostTreeItem | null | undefined {

export async function editExportPost(input: unknown): Promise<void> {
const target = parseInput(input)
if (!target) return void Alert.warn('不支持的参数输入')
if (target === undefined || target === null) return void Alert.warn('不支持的参数输入')

const {
post: { title, isMarkdown, id: postId },
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/blog-export/open-local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,6 @@ export async function openLocalExport(opts: Partial<typeof defaultOptions> = def
)
await DownloadedExportStore.add(dbFilePath, exportRecord?.id)

if (exportRecord) await treeProvider?.refreshRecords({ force: false })
if (exportRecord !== undefined) await treeProvider?.refreshRecords({ force: false })
else await treeProvider?.refreshDownloadedExports()
}
16 changes: 6 additions & 10 deletions src/cmd/blog-export/view-post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ async function provide(downloadedExport: DownloadedBlogExport, { id: postId, tit

return false
})
if (matchedEditor) {
if (matchedEditor !== undefined) {
await window.showTextDocument(matchedEditor.document, { preview: false, preserveFocus: true })
return
}
Expand All @@ -45,15 +45,11 @@ async function provide(downloadedExport: DownloadedBlogExport, { id: postId, tit
})()
)

const document = await workspace
.openTextDocument(Uri.parse(`${schemaWithId}:(只读) ${title}.${isMarkdown ? 'md' : 'html'}?postId=${postId}`))
.then(x => x, console.warn)
if (document) {
await window.showTextDocument(document).then(undefined, console.warn)
await languages
.setTextDocumentLanguage(document, isMarkdown ? 'markdown' : 'html')
.then(undefined, console.warn)
}
const uri = Uri.parse(`${schemaWithId}:(只读) ${title}.${isMarkdown ? 'md' : 'html'}?postId=${postId}`)
const document = await workspace.openTextDocument(uri)

await window.showTextDocument(document)
await languages.setTextDocumentLanguage(document, isMarkdown ? 'markdown' : 'html')

disposable.dispose()
}
5 changes: 3 additions & 2 deletions src/cmd/extract-img/extract-img.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import { findImgLink } from '@/cmd/extract-img/find-img-link'
import { convertImgInfo } from '@/cmd/extract-img/convert-img-info'
import { dirname } from 'path'

export async function extractImg(arg: unknown, inputImgSrc?: ImgSrc) {
if (!(arg instanceof Uri && arg.scheme === 'file')) return
export async function extractImg(arg?: Uri, inputImgSrc?: ImgSrc) {
if (arg === undefined) return
if (arg.scheme !== 'file') return

const editor = window.visibleTextEditors.find(x => x.document.fileName === arg.fsPath)
const textDocument = editor?.document ?? workspace.textDocuments.find(x => x.fileName === arg.fsPath)
Expand Down
10 changes: 5 additions & 5 deletions src/cmd/ing/comment-ing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@ export class CommentIngCmdHandler implements CmdHandler {

async handle(): Promise<void> {
const maxIngContentLength = 50
const baseTitle = this._parentCommentId || 0 > 0 ? `回复@${this._atUser?.displayName}` : '评论闪存'
const baseTitle = this._parentCommentId !== undefined ? `回复@${this._atUser?.displayName}` : '评论闪存'
const input = await window.showInputBox({
title: `${baseTitle}: ${this._ingContent.substring(0, maxIngContentLength)}${
this._ingContent.length > maxIngContentLength ? '...' : ''
}`,
prompt: this._atUser ? `@${this._atUser.displayName}` : '',
prompt: this._atUser !== undefined ? `@${this._atUser.displayName}` : '',
ignoreFocusOut: true,
})
this._content = input || ''
this._content = input ?? ''
const { id: atUserId, displayName: atUserAlias } = this._atUser ?? {}
const atContent = atUserAlias ? `@${atUserAlias} ` : ''
const atContent = atUserAlias !== undefined ? `@${atUserAlias} ` : ''

if (this._content) {
if (this._content !== '') {
return window.withProgress({ location: ProgressLocation.Notification, title: '正在请求...' }, async p => {
p.report({ increment: 30 })
const isSuccess = await IngService.comment(
Expand Down
12 changes: 5 additions & 7 deletions src/cmd/ing/ing-page-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,11 @@ export namespace Ing.ListView {

quickPick.onDidChangeSelection(
([selectedItem]) => {
if (selectedItem) {
quickPick.hide()
return getIngListWebviewProvider().refreshingList({
pageIndex: 1,
ingType: selectedItem.ingType,
})
}
quickPick.hide()
return getIngListWebviewProvider().refreshingList({
pageIndex: 1,
ingType: selectedItem.ingType,
})
},
undefined,
disposables
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/ing/pub-ing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ async function afterPub(ingIsPrivate: boolean) {

const selected = await Alert.info('闪存已发布, 快去看看吧', ...options.map(v => ({ title: v[0], id: v[0] })))

if (selected) return options.find(x => x[0] === selected.id)?.[1]()
if (selected !== undefined) return options.find(x => x[0] === selected.id)?.[1]()
}

export function pubIng(content: string, isPrivate: boolean) {
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/open/open-post-in-blog-admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { Post } from '@/model/post'
import { PostFileMapManager } from '@/service/post/post-file-map'
import { PostTreeItem } from '@/tree-view/model/post-tree-item'

export const openPostInBlogAdmin = (item: Post | PostTreeItem | Uri) => {
if (!item) return
export const openPostInBlogAdmin = (item?: Post | PostTreeItem | Uri) => {
if (item === undefined) return

item = item instanceof PostTreeItem ? item.post : item
const postId = item instanceof Post ? item.id : PostFileMapManager.getPostId(item.fsPath) ?? -1
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/open/os-open-local-post-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { execCmd } from '@/infra/cmd'
import { Post } from '@/model/post'
import { PostFileMapManager } from '@/service/post/post-file-map'

export function osOpenLocalPostFile(post: Post | undefined) {
export function osOpenLocalPostFile(post?: Post) {
if (post === undefined) return

const postFilePath = PostFileMapManager.getFilePath(post.id)
Expand Down
Loading

0 comments on commit 1dfe1a4

Please sign in to comment.