Files

878 lines
24 KiB
TypeScript
Raw Permalink Normal View History

// main.ts
import { ItemView, setIcon, Modal, App, Notice, MarkdownView } from "obsidian";
import i18n from "../utils/i18n";
import { getSettings } from "../main";
import { HttpUtils } from "../utils/request";
import { Util } from "../utils/util";
import { BrowseArticles } from "./browse_articles";
// 图片预览模态框
class ImageModal extends Modal {
file: any;
constructor(app: App, file: any) {
super(app);
this.file = file;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass("image-preview-modal");
// 创建图片容器
const imageContainer = contentEl.createDiv({
cls: "image-preview-container",
});
// 创建图片标题
imageContainer.createEl("h2", {
text: this.file.title,
cls: "image-preview-title",
});
// 创建图片信息
const infoContainer = imageContainer.createDiv({
cls: "image-preview-info",
});
infoContainer.createEl("span", {
text: `${i18n.t("field.type")}: ${this.file.type.toUpperCase()}`,
cls: "image-info-item",
});
infoContainer.createEl("span", {
text: `${i18n.t("field.size")}: ${this.formatFileSize(this.file.size)}`,
cls: "image-info-item",
});
infoContainer.createEl("span", {
text: `${i18n.t("field.time")}: ${this.file.createdAt}`,
cls: "image-info-item",
});
// 创建图片元素
const img = imageContainer.createEl("img", {
cls: "image-preview-img",
attr: { src: this.file.url },
});
}
// 格式化文件大小
formatFileSize(size: number): string {
if (size < 1024) {
return size + " B";
} else if (size < 1024 * 1024) {
return (size / 1024).toFixed(2) + " KB";
} else {
return (size / (1024 * 1024)).toFixed(2) + " MB";
}
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
const VIEW_TYPE = "obsidian-to-typecho-view";
class CategoryView extends ItemView {
pageSize = 15; // 默认每页显示15条
getViewType(): string {
return VIEW_TYPE;
}
getDisplayText() {
return i18n.t("field.category");
}
getIcon(): string {
return "typecho";
}
async onOpen() {
const container = this.containerEl.children[1];
container.empty();
// 创建选项卡导航
const tabContainer = container.createDiv({ cls: "tab-container" });
const tabs = [
{ key: "all", label: i18n.t("field.allArticle") },
{ key: "category", label: i18n.t("field.category") },
{ key: "tag", label: i18n.t("field.tag") },
{ key: "file", label: i18n.t("field.file") },
];
// 初始化加载第一个 tab
this.currentTab = "category";
tabs.forEach((tab) => {
const tabEl = tabContainer.createEl("span", {
text: tab.label,
cls:
"tab-span " +
(tab.key === this.currentTab ? "selected" : ""),
});
tabEl.addEventListener("click", async () => {
if (tab.key == "all") {
new BrowseArticles(
this.app,
{ name: i18n.t("field.allArticle") },
"all"
).open();
return;
}
this.switchTab(tab.key, tabContainer, tabEl);
});
});
// 内容容器
this.contentContainer = container.createDiv({ cls: "tab-content" });
// 刷新按钮
const refreshButton = tabContainer.createEl("button", {
cls: "refresh-button",
});
setIcon(refreshButton, "rotate-ccw");
refreshButton.addEventListener("click", () => {
this.loadData(this.currentTab, this.contentContainer);
});
this.loadData("category", this.contentContainer);
}
switchTab(tabKey: string, tabContainer: HTMLElement, tabEl: HTMLElement) {
const selectedTabs =
tabContainer.querySelectorAll(".tab-span.selected");
selectedTabs.forEach((tab: HTMLElement) => {
tab.classList.remove("selected");
});
tabEl.classList.add("selected");
this.currentTab = tabKey;
this.contentContainer.empty();
this.loadData(tabKey, this.contentContainer);
}
currentTab: string;
contentContainer: HTMLElement;
async loadData(tabKey: string, container: Element) {
container.empty();
// 修改:使用 HttpUtils.getCurrentUserUid() 判断
if (!HttpUtils.getCurrentUserUid()) {
container.createEl("p", {
text: i18n.t("error.noTypechoUser"),
});
return;
}
let data: any[] = [];
if (tabKey === "category") {
const response = await HttpUtils.get("/categories", {});
data = Util.treeUtil.generateTreeData(
response.data,
"mid",
"parent"
);
const treeContainer = container.createDiv({
cls: "tree-container",
});
this.renderTree(treeContainer, data);
} else if (tabKey === "tag") {
const response = await HttpUtils.get("/tags", {});
data = Util.treeUtil.generateTreeData(
response.data,
"mid",
"parent"
);
const treeContainer = container.createDiv({
cls: "tree-container",
});
this.renderTree(treeContainer, data);
} else if (tabKey === "file") {
await this.loadFileList(container, 1);
}
}
async loadFileList(container: Element, page = 1) {
container.empty();
// 创建上传按钮和分页设置区域
const uploadContainer = container.createDiv({
cls: "upload-container",
});
// 创建分页设置区域
const pageSizeContainer = uploadContainer.createDiv({
cls: "page-size-container",
});
// 添加分页大小标签
pageSizeContainer.createEl("span", {
text: i18n.t("file.itemsPerPage") + ": ",
cls: "page-size-label",
});
// 创建分页大小选择器
const pageSizeSelect = pageSizeContainer.createEl("select", {
cls: "page-size-select",
});
// 添加选项
[10, 15, 20, 30, 50].forEach((size) => {
const option = pageSizeSelect.createEl("option", {
text: size.toString(),
value: size.toString(),
});
if (size === this.pageSize) {
option.selected = true;
}
});
// 添加选择事件
pageSizeSelect.addEventListener("change", () => {
this.pageSize = parseInt(pageSizeSelect.value);
this.loadFileList(container, 1); // 重新加载第一页
});
// 上传按钮
const uploadButton = uploadContainer.createEl("button", {
text: i18n.t("file.uploadFile"),
cls: "upload-button",
});
setIcon(uploadButton, "upload");
// 上传按钮点击事件
uploadButton.addEventListener("click", () => {
this.uploadFile(container, page);
});
const response = await HttpUtils.get(
`/fileList?page=${page}&pageSize=${this.pageSize}`,
{}
);
const fileData = response.data;
if (!fileData || !fileData.dataSet || fileData.dataSet.length === 0) {
container.createEl("p", {
text: i18n.t("error.noFiles"),
});
return;
}
// 修改:使用 HttpUtils.getCurrentHost()
fileData.dataSet.forEach((file: any) => {
file.url = Util.url.extractDomain(HttpUtils.getCurrentHost()) + file.path;
});
// 创建文件列表容器
const fileListContainer = container.createDiv({
cls: "file-list-container",
});
// 创建文件列表
const fileList = fileListContainer.createEl("ul", { cls: "file-list" });
// 添加文件项
fileData.dataSet.forEach((file: any) => {
const fileItem = fileList.createEl("li", { cls: "file-item" });
// 创建左侧信息区域
const infoContainer = fileItem.createDiv({
cls: "file-info-container",
});
// 如果是图片类型,添加缩略图预览
if (file.mime && file.mime.startsWith("image/")) {
const previewContainer = infoContainer.createDiv({
cls: "file-preview-container",
});
const previewImg = previewContainer.createEl("img", {
cls: "file-preview-img",
attr: { src: file.url },
});
// 点击图片弹出大屏预览
previewImg.addEventListener("click", (e) => {
e.stopPropagation();
this.showImageModal(file);
});
}
// 创建文件信息区域
const textContainer = infoContainer.createDiv({
cls: "file-text-container",
});
// 文件标题
textContainer.createEl("div", {
text: file.title,
cls: "file-title",
});
// 文件类型
textContainer.createEl("div", {
text: file.type ? file.type.toUpperCase() : "",
cls: "file-type",
});
// 创建右侧信息区域
const metaContainer = fileItem.createDiv({
cls: "file-meta-container",
});
// 文件时间
metaContainer.createEl("div", {
text: file.createdAt || "",
cls: "file-time",
});
// 操作按钮容器
const actionContainer = metaContainer.createDiv({
cls: "file-action-container",
});
// 复制URL按钮
const copyButton = actionContainer.createEl("button", {
cls: "file-action-button copy-button",
attr: { title: i18n.t("file.copyUrl") },
});
setIcon(copyButton, "link");
// 复制URL按钮点击事件
copyButton.addEventListener("click", (e) => {
e.stopPropagation();
this.copyToClipboard(file.url, file.title);
});
// 插入按钮
const insertButton = actionContainer.createEl("button", {
cls: "file-action-button insert-button",
attr: { title: i18n.t("file.insertToEditor") },
});
setIcon(insertButton, "document");
insertButton.addEventListener("click", async (e) => {
e.stopPropagation();
await this.insertToEditor(file.url, file.title);
});
// 删除按钮
const deleteButton = actionContainer.createEl("button", {
cls: "file-action-button delete-button",
attr: { title: i18n.t("file.deleteFile") },
});
setIcon(deleteButton, "trash");
// 删除按钮点击事件
deleteButton.addEventListener("click", async (e) => {
e.stopPropagation();
if (
!confirm(i18n.t("file.deleteConfirm", { fileName: file.title }))
) {
return;
}
// 只有真的删掉了才刷新列表,失败时保持原样等用户重试
if (await this.deleteFile(file.cid)) {
this.loadFileList(container, page);
}
});
});
// 添加分页控件
if (fileData.pages > 1) {
const paginationContainer = container.createDiv({
cls: "pagination-container",
});
// 上一页按钮
if (fileData.page > 1) {
const prevButton = paginationContainer.createEl("button", {
text: i18n.t("common.previousPage"),
cls: "pagination-button",
});
prevButton.addEventListener("click", () => {
this.loadFileList(container, fileData.page - 1);
});
}
// 页码信息
paginationContainer.createEl("span", {
text: `${fileData.page}/${fileData.pages}`,
cls: "pagination-info",
});
// 下一页按钮
if (fileData.page < fileData.pages) {
const nextButton = paginationContainer.createEl("button", {
text: i18n.t("common.nextPage"),
cls: "pagination-button",
});
nextButton.addEventListener("click", () => {
this.loadFileList(container, fileData.page + 1);
});
}
}
}
renderTree(container: Element, nodes: any[], depth = 0) {
const ul = container.createEl("ul", { cls: "tree-node-list" });
for (const node of nodes) {
const li = ul.createEl("li");
const wrapper = li.createDiv({ cls: "tree-node-wrapper" });
const indent = wrapper.createSpan({ cls: "tree-indent" });
indent.style.paddingLeft = `${depth * 16}px`;
if (node.children && node.children.length > 0) {
const toggleIcon = wrapper.createEl("span", {
text: node.isExpanded ? "▼" : "▶",
cls: "tree-toggle-icon",
});
toggleIcon.addEventListener("click", (e) => {
e.stopPropagation();
node.isExpanded = !node.isExpanded;
toggleIcon.setText(node.isExpanded ? "▼" : "▶");
if (node.isExpanded) {
const childContainer =
li.querySelector(".tree-children") ||
li.createEl("div", { cls: "tree-children" });
childContainer.empty();
this.renderTree(
childContainer,
node.children,
depth + 1
);
} else {
const childContainer =
li.querySelector(".tree-children");
if (childContainer) childContainer.remove();
}
});
}
wrapper.createEl("span", {
text: node.name,
cls: "tree-node-label",
});
if (node.count && node.count > 0) {
const articleIcon = wrapper.createEl("span", {
cls: "tree-article-icon",
});
setIcon(articleIcon, "newspaper");
articleIcon.addEventListener("click", (e) => {
e.stopPropagation();
new BrowseArticles(this.app, node, this.currentTab).open();
});
}
if (node.children && node.children.length > 0 && node.isExpanded) {
const childContainer = li.createEl("div", {
cls: "tree-children",
});
this.renderTree(childContainer, node.children, depth + 1);
}
}
}
// 显示图片大屏预览
showImageModal(file: any) {
const modal = new ImageModal(this.app, file);
modal.open();
}
// 删除文件
async deleteFile(cid: number) {
try {
const response = await HttpUtils.post("/deleteFile", { cid });
if (response) {
new Notice(i18n.t("file.deleteSuccess"));
return true;
}
return false;
} catch (error) {
console.error("delete file failed:", error);
// 具体原因(文件不存在 / 未登录 / 服务器报错)HttpUtils 已经弹过
HttpUtils.notifyError(error, i18n.t("file.deleteError"));
return false;
}
}
// 复制URL到剪贴板
copyToClipboard(url: string, fileName: string) {
if (!url) {
new Notice(i18n.t("file.copyFailed"));
return;
}
// 创建临时文本区域
const textarea = document.createElement("textarea");
textarea.value = url;
textarea.style.position = "absolute";
textarea.style.left = "-9999px";
document.body.appendChild(textarea);
// 选择并复制
textarea.select();
document.execCommand("copy");
// 移除临时元素
document.body.removeChild(textarea);
// 显示成功提示
new Notice(i18n.t("file.copySuccess", { fileName: fileName }));
}
/**
* 获取当前活动的编辑器实例(兼容各种插件冲突)
* 使用多种方式尝试获取,确保在各种情况下都能正常工作
*/
private getActiveEditor(): any {
try {
// 方法1: 通过 getActiveViewOfType 获取活动的 Markdown 视图
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView && markdownView.editor) {
return markdownView.editor;
}
// 方法2: 通过 activeLeaf 获取
const activeLeaf = this.app.workspace.activeLeaf;
if (activeLeaf && activeLeaf.view instanceof MarkdownView) {
return activeLeaf.view.editor;
}
// 方法3: 遍历所有 Markdown 视图
const leaves = this.app.workspace.getLeavesOfType("markdown");
for (const leaf of leaves) {
if (leaf.view instanceof MarkdownView) {
return leaf.view.editor;
}
}
// 方法4: 遍历所有叶子节点(兜底)
// 使用 getLeavesOfType 传入空字符串获取所有叶子
const allLeaves = this.app.workspace.getLeavesOfType("");
for (const leaf of allLeaves) {
if (leaf.view instanceof MarkdownView) {
return leaf.view.editor;
}
}
return null;
} catch (error) {
console.error("获取编辑器实例失败:", error);
return null;
}
}
/**
* 插入图片到当前编辑器
* 修复了与写作助手等插件冲突的问题
*/
async insertToEditor(url: string, fileName: string) {
try {
// 使用增强的编辑器获取方法
const editor = this.getActiveEditor();
if (!editor) {
new Notice(i18n.t("error.noEditor"));
return false;
}
// 生成插入文本
let title = fileName.replace(/\.[^/.]+$/, "");
const insertText = `![${title}](${url})`;
// 获取当前光标位置并插入
const cursor = editor.getCursor();
editor.replaceRange(insertText, cursor);
// 可选:聚焦到编辑器
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
this.app.workspace.revealLeaf(activeView.leaf);
}
new Notice(i18n.t("error.inserted", { title }));
return true;
} catch (error) {
console.error("insert to editor failed:", error);
new Notice(
i18n.t("error.insertFailed", {
message:
(error as any)?.message || i18n.t("error.unknownError"),
})
);
return false;
}
}
// 上传文件(单/多文件,带进度条 + 限速延迟)
uploadFile(container: Element, page: number) {
const fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.multiple = true;
fileInput.style.display = "none";
document.body.appendChild(fileInput);
fileInput.addEventListener("change", async () => {
const files = Array.from(fileInput.files || []);
if (files.length === 0) {
document.body.removeChild(fileInput);
return;
}
// 创建上传进度面板
const progressPanel = this.createUploadProgressPanel(files.length);
document.body.appendChild(progressPanel.element);
let isCancelled = false;
// 取消按钮逻辑
if (progressPanel.cancelButton) {
progressPanel.cancelButton.onclick = () => {
isCancelled = true;
progressPanel.updateStatus(i18n.t("file.uploadCancelled"));
progressPanel.setProgress(0);
setTimeout(() => progressPanel.hide(), 1000);
};
}
try {
progressPanel.updateStatus(i18n.t("file.preparingUpload"));
for (let i = 0; i < files.length; i++) {
if (isCancelled) break;
const file = files[i];
const current = i + 1;
const total = files.length;
progressPanel.updateFile(file.name);
progressPanel.updateStatus(
i18n.t("file.uploadingProgress", { current, total })
);
progressPanel.setProgress(((current - 1) / total) * 100); // 上传前进度
try {
const buffer = await Util.file.fileToUint8Array(file);
// 修改:使用 HttpUtils.getCurrentUserUid()
const response = await HttpUtils.post(
"/upload?authorId=" + HttpUtils.getCurrentUserUid(),
{
file: buffer,
fileName: file.name,
}
);
if (!response) {
throw new Error("Upload response is empty");
}
// ✅ 单文件上传成功,更新进度为当前文件完成
progressPanel.setProgress((current / total) * 100);
// ⏱️ 限流延迟
if (i < files.length - 1) {
const delayMs =
300 + Math.floor(Math.random() * 300); // 300~600ms
await new Promise((resolve) =>
setTimeout(resolve, delayMs)
);
}
} catch (err) {
console.error(`Failed to upload ${file.name}:`, err);
progressPanel.updateStatus(
i18n.t("file.uploadItemFailed", {
fileName: file.name,
})
);
progressPanel.setProgress((current / total) * 100);
await new Promise((resolve) =>
setTimeout(resolve, 500)
);
}
}
if (isCancelled) {
progressPanel.updateStatus(i18n.t("file.uploadCancelled"));
} else {
progressPanel.updateStatus(i18n.t("file.uploadAllDone"));
progressPanel.setProgress(100);
await new Promise((resolve) => setTimeout(resolve, 1000));
this.loadFileList(container, page); // 刷新列表
}
} catch (error) {
console.error("Upload process error:", error);
progressPanel.updateStatus(i18n.t("file.uploadProcessError"));
} finally {
// 自动隐藏
setTimeout(
() => progressPanel.hide(),
isCancelled ? 1500 : 2000
);
document.body.removeChild(fileInput);
}
});
fileInput.click();
}
// 辅助方法:创建上传进度面板
private createUploadProgressPanel(totalFiles: number) {
const panel = document.createElement("div");
panel.className = "obsidian-upload-progress-panel";
// CSS 注入(一次性,防止重复)
if (!document.getElementById("upload-progress-style")) {
const style = document.createElement("style");
style.id = "upload-progress-style";
style.textContent = `
.obsidian-upload-progress-panel {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 9999;
background: var(--background-secondary);
border: 1px solid var(--background-modifier-border);
border-radius: 8px;
padding: 12px 16px;
min-width: 300px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
font-size: var(--font-ui-smaller);
transition: opacity 0.3s, transform 0.3s;
opacity: 1;
transform: translateY(0);
}
.obsidian-upload-progress-panel.fade-out {
opacity: 0;
transform: translateY(20px);
}
.upload-progress-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.upload-progress-title {
font-weight: 600;
color: var(--text-normal);
}
.upload-progress-cancel {
background: none;
border: none;
color: var(--text-muted);
cursor: pointer;
font-size: 16px;
padding: 2px;
border-radius: 4px;
}
.upload-progress-cancel:hover {
color: var(--text-accent);
background: var(--background-modifier-hover);
}
.upload-progress-filename {
color: var(--text-faint);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 4px;
}
.upload-progress-bar-container {
width: 100%;
height: 6px;
background: var(--background-modifier-border);
border-radius: 3px;
overflow: hidden;
margin: 6px 0;
}
.upload-progress-bar {
height: 100%;
background: var(--interactive-accent);
border-radius: 3px;
width: 0%;
transition: width 0.3s ease;
}
.upload-progress-status {
font-size: var(--font-ui-smaller);
color: var(--text-muted);
display: flex;
justify-content: space-between;
}
`;
document.head.appendChild(style);
}
panel.innerHTML = `
<div class="upload-progress-header">
<span class="upload-progress-title">${i18n.t("file.uploadPanelTitle")}</span>
<button class="upload-progress-cancel" title="${i18n.t("file.cancelUpload")}">×</button>
</div>
<div class="upload-progress-filename">-</div>
<div class="upload-progress-bar-container">
<div class="upload-progress-bar"></div>
</div>
<div class="upload-progress-status">
<span class="status-text">${i18n.t("file.preparing")}</span>
<span class="progress-percent">0%</span>
</div>
`;
const filenameEl = panel.querySelector(
".upload-progress-filename"
) as HTMLElement;
const barEl = panel.querySelector(
".upload-progress-bar"
) as HTMLElement;
const statusEl = panel.querySelector(".status-text") as HTMLElement;
const percentEl = panel.querySelector(
".progress-percent"
) as HTMLElement;
const cancelButton = panel.querySelector(
".upload-progress-cancel"
) as HTMLElement;
const api = {
element: panel,
cancelButton,
updateFile(filename: string) {
filenameEl.textContent = filename;
},
updateStatus(text: string) {
statusEl.textContent = text;
},
setProgress(percent: number) {
const p = Math.max(0, Math.min(100, Math.round(percent)));
barEl.style.width = `${p}%`;
percentEl.textContent = `${p}%`;
},
hide() {
panel.classList.add("fade-out");
setTimeout(() => {
if (panel.parentNode) panel.parentNode.removeChild(panel);
}, 300);
},
};
return api;
}
async onClose() {
// 清理资源
}
}
export { CategoryView, VIEW_TYPE };