Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: files panel #128

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from
Draft
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: 2 additions & 0 deletions components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ declare module 'vue' {
AppProvider: typeof import('./src/components/AppProvider.vue')['default']
MarkdownRender: typeof import('./src/components/MarkdownRender.vue')['default']
NAlert: typeof import('naive-ui')['NAlert']
NBreadcrumb: typeof import('naive-ui')['NBreadcrumb']
NBreadcrumbItem: typeof import('naive-ui')['NBreadcrumbItem']
NButton: typeof import('naive-ui')['NButton']
NCard: typeof import('naive-ui')['NCard']
NCollapse: typeof import('naive-ui')['NCollapse']
Expand Down
9 changes: 5 additions & 4 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"@types/debug": "^4.1.12",
"@types/jest": "^29.5.12",
"@types/markdown-it": "^14.1.1",
"@types/lodash": "^4.17.12",
"@typescript-eslint/eslint-plugin": "^7.14.1",
"@typescript-eslint/parser": "^7.14.1",
"@vicons/antd": "^0.12.0",
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ edition = "2021"
tauri-build = { version = "1.5", features = [] }

[dependencies]
tauri = { version = "1.7", features = [ "dialog-open", "fs-create-dir", "global-shortcut-all", "http-all", "fs-exists", "fs-read-file", "fs-write-file", "shell-open"] }
tauri = { version = "1.7", features = [ "fs-remove-dir", "fs-remove-file", "fs-rename-file", "fs-read-dir", "dialog-open", "fs-create-dir", "global-shortcut-all", "http-all", "fs-exists", "fs-read-file", "fs-write-file", "shell-open"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1"
tauri-plugin-store = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
Expand Down
8 changes: 5 additions & 3 deletions src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@
"writeFile": true,
"createDir": true,
"exists": true,
"scope": [
"$APPDATA/**/*"
]
"readDir": true,
"removeDir": true,
"removeFile": true,
"renameFile": true,
"scope": ["*/**"]
},
"http": {
"all": true,
Expand Down
37 changes: 35 additions & 2 deletions src/datasources/sourceFileApi.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { BaseDirectory, createDir, exists, readTextFile, writeTextFile } from '@tauri-apps/api/fs';
import {
BaseDirectory,
createDir,
exists,
readTextFile,
removeDir,
removeFile,
renameFile,
writeTextFile,
} from '@tauri-apps/api/fs';

import { debug } from '../common';
import { CustomError, debug } from '../common';

const saveFile = async (filePath: string, content: string) => {
try {
Expand Down Expand Up @@ -31,9 +40,33 @@ const readFromFile = async (filePath: string) => {
}
};

const deleteFileOrFolder = async (filePath: string) => {
try {
await Promise.any([removeFile(filePath), removeDir(filePath, { recursive: true })]);
debug('delete file or folder success');
} catch (err) {
console.log(`deleteFileOrFolder error`, JSON.stringify(err));
debug(`deleteFileOrFolder error: ${err}`);
throw new CustomError(500, JSON.stringify(err));
}
};

const renameFileOrFolder = async (oldPath: string, newPath: string) => {
try {
await renameFile(oldPath, newPath);
debug('rename file or folder success');
} catch (err) {
debug(`renameFileOrFolder error: ${err}`);
throw new CustomError(500, JSON.stringify(err));
}
};

const sourceFileApi = {
saveFile: (filePath: string, content: string) => saveFile(filePath, content),
readFile: (filePath: string) => readFromFile(filePath),
createFolder: (folderPath: string) => createDir(folderPath),
deleteFileOrFolder,
renameFileOrFolder,
};

export { sourceFileApi };
12 changes: 12 additions & 0 deletions src/lang/enUS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,18 @@ export const enUS = {
invalidJson: 'Invalid JSON format',
copySuccess: 'Copied to clipboard',
copyFailure: 'Failed to copy to clipboard',
unsupportedFile: 'DocKit does not support this file type',
},
file: {
newFile: 'New File',
newFolder: 'New Folder',
open: 'Open Folder',
contextMenu: {
open: 'Open',
rename: 'Rename',
delete: 'Delete',
},
name: 'Name',
},
history: {
empty: 'No history yet',
Expand Down
13 changes: 13 additions & 0 deletions src/lang/zhCN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,19 @@ export const zhCN = {
invalidJson: '无效的 JSON 格式',
copySuccess: '已复制到粘贴板',
copyFailure: '复制失败',
unsupportedFile: 'DocKit不支持该文件类型',
},
file: {
newFile: '新建文件',
newFolder: '新建文件夹',
open: '打开文件夹',
name: '名称',
validationFailed: '表单验证失败!',
contextMenu: {
open: '打开',
rename: '重命名',
delete: '删除',
},
},
history: {
empty: '无历史记录',
Expand Down
9 changes: 4 additions & 5 deletions src/router/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { createMemoryHistory, createRouter } from 'vue-router';

import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../store';

const LOGIN_PATH = '/login';

const router = createRouter({
history: createMemoryHistory(),
history: createWebHistory(),
scrollBehavior: () => ({ left: 0, top: 0 }),
routes: [
{
Expand All @@ -23,11 +22,11 @@ const router = createRouter({
keepAlive: false,
},
component: () => import('../layout/index.vue'),
redirect: '/connect',
redirect: '/connect/:filePath?',
children: [
{
name: 'Connect',
path: '/connect',
path: '/connect/:filePath?',
meta: {
keepAlive: false,
},
Expand Down
91 changes: 84 additions & 7 deletions src/store/sourceFileStore.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,99 @@
import { open } from '@tauri-apps/api/dialog';
import { exists, readDir } from '@tauri-apps/api/fs';
import { defineStore } from 'pinia';
import { sourceFileApi } from '../datasources';
import { CustomError } from '../common';
import { get } from 'lodash';

const sourceFilePath = 'search/default.search';

export enum ToolBarAction {
ADD_DOCUMENT = 'ADD_DOCUMENT',
ADD_FOLDER = 'ADD_FOLDER',
OPEN_FOLDER = 'OPEN_FOLDER',
}

export enum FileType {
FILE = 'FILE',
FOLDER = 'FOLDER',
}

export type FileItem = {
path: string;
name: string | undefined;
type: FileType;
};

export const useSourceFileStore = defineStore('sourceFileStore', {
state(): { defaultFile: string } {
state(): { fileContent: string; filePath: string; folderPath?: string; fileList: FileItem[] } {
return {
defaultFile: '',
fileContent: '',
filePath: '',
folderPath: '',
fileList: [],
};
},
persist: true,
getters: {},
actions: {
async readSourceFromFile() {
this.defaultFile = await sourceFileApi.readFile(sourceFilePath);
async readSourceFromFile(path: string | undefined) {
this.filePath = path && path !== ':filePath' ? path : sourceFilePath;
this.fileContent = await sourceFileApi.readFile(this.filePath);
},
async saveSourceToFile(content: string, path: string | undefined) {
if (path && path !== ':filePath' && path !== this.filePath) {
this.filePath = path;
}
this.fileContent = content;
await sourceFileApi.saveFile(this.filePath, content);
},

async openFolder(path?: string) {
try {
const selectedPath =
path ?? ((await open({ recursive: true, directory: true, defaultPath: path })) as string);

if (!(await exists(selectedPath))) {
throw new CustomError(404, 'Folder not found');
}

this.fileList = (await readDir(selectedPath))
.filter(file => !file.name?.startsWith('.'))
.sort((a, b) => {
if (a.children && !b.children) return -1;
if (!a.children && b.children) return 1;
return a?.name?.localeCompare(b?.name ?? '') || 0;
})
.map(file => ({
path: file.path,
name: file.name,
type: file.children ? FileType.FOLDER : FileType.FILE,
}));

this.folderPath = selectedPath;
} catch (error) {
throw new CustomError(
get(error, 'status', 500),
get(error, 'details', get(error, 'message', '')),
);
}
},
async createFileOrFolder(action: ToolBarAction, name: string) {
const targetPath = `${this.folderPath}/${name}`;
if (action === ToolBarAction.ADD_DOCUMENT) {
await sourceFileApi.saveFile(targetPath, '');
} else {
await sourceFileApi.createFolder(targetPath);
}
await this.openFolder(this.folderPath);
},
async deleteFileOrFolder(path: string) {
await sourceFileApi.deleteFileOrFolder(path);
await this.openFolder(this.folderPath);
},
async saveSourceToFile(content: string) {
this.defaultFile = content;
await sourceFileApi.saveFile(sourceFilePath, content);
async renameFileOrFolder(oldPath: string, newPath: string) {
await sourceFileApi.renameFileOrFolder(oldPath, newPath);
await this.openFolder(this.folderPath);
},
},
});
31 changes: 22 additions & 9 deletions src/views/editor/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
</n-split>
</template>
<script setup lang="ts">
import { useRoute } from 'vue-router';
import { open } from '@tauri-apps/api/shell';
import { listen } from '@tauri-apps/api/event';
import { storeToRefs } from 'pinia';
Expand Down Expand Up @@ -42,9 +43,11 @@ const appStore = useAppStore();
const message = useMessage();
const lang = useLang();

const route = useRoute();

const sourceFileStore = useSourceFileStore();
const { readSourceFromFile, saveSourceToFile } = sourceFileStore;
const { defaultFile } = storeToRefs(sourceFileStore);
const { fileContent } = storeToRefs(sourceFileStore);

const connectionStore = useConnectionStore();
const { searchQDSL, queryToCurl } = connectionStore;
Expand Down Expand Up @@ -331,23 +334,33 @@ const displayJsonEditor = (content: string) => {
displayEditorRef.value.display(content);
};

const unlistenSaveFile = ref<Function>();
const saveFileListener = async () => {
unlistenSaveFile.value = await listen('saveFile', async () => {
if (!queryEditor) {
return;
}
await saveSourceToFile(
queryEditor?.getModel()?.getValue() || '',
route.params.filePath as string,
);
});
};

onMounted(async () => {
await readSourceFromFile();
const code = defaultFile.value;
await readSourceFromFile(route.params.filePath as string);
const code = fileContent.value;
await saveFileListener();
setupQueryEditor(code);
});

onUnmounted(() => {
codeLensProvider?.dispose();
queryEditor?.dispose();
displayEditorRef?.value?.dispose();
});
// @ts-ignore
listen('saveFile', async event => {
if (!queryEditor) {
return;
if (unlistenSaveFile?.value) {
unlistenSaveFile.value();
}
await saveSourceToFile(queryEditor?.getModel()?.getValue() || '');
});
</script>

Expand Down
Loading
Loading