15 Commits
23 changed files with 1944 additions and 289 deletions

No files matched your search

+11 -5
View File
@@ -1,5 +1,11 @@
# Vue 3 + TypeScript + Vite todo: 标签页,miaoDirectory切换动画 [finish]
todo: 重构virtualPage,所有page以插件形式使用 [finish]
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more. todo: miaoDirectory插件化,为后续插件功能开发做准备 [finish]
todo: miaoPopupInput, 弹出一个输入框 [finish]
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup). todo: miaoDirectory的重命名功能 [finish]
todo: miaoDirectory的剪切功能 [finish]
todo: miaoDirectory的上传按钮 [finish]
todo: miaoDirectory的新建文件/文件夹功能 [finish]
todo: miaoDirectory的多选功能 [finish]
todo: VirtualDirectory更新时更新文件信息
todo: miaoDirectory的复制文件/文件夹功能
+5
View File
@@ -5,20 +5,25 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"dev:host": "vite --host 0.0.0.0",
"build": "vue-tsc -b && vite build", "build": "vue-tsc -b && vite build",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@vicons/ionicons5": "^0.12.0", "@vicons/ionicons5": "^0.12.0",
"axios": "^1.7.3",
"lodash": "^4.17.21",
"naive-ui": "^2.39.0", "naive-ui": "^2.39.0",
"sass": "^1.77.8", "sass": "^1.77.8",
"vue": "^3.4.35" "vue": "^3.4.35"
}, },
"devDependencies": { "devDependencies": {
"@types/lodash": "^4.17.7",
"@types/node": "^22.1.0", "@types/node": "^22.1.0",
"@vitejs/plugin-vue": "^5.1.2", "@vitejs/plugin-vue": "^5.1.2",
"typescript": "^5.5.3", "typescript": "^5.5.3",
"vite": "^5.4.0", "vite": "^5.4.0",
"vite-plugin-singlefile": "^2.0.2",
"vue-tsc": "^2.0.29" "vue-tsc": "^2.0.29"
} }
} }
+104
View File
@@ -11,6 +11,12 @@ importers:
'@vicons/ionicons5': '@vicons/ionicons5':
specifier: ^0.12.0 specifier: ^0.12.0
version: 0.12.0 version: 0.12.0
axios:
specifier: ^1.7.3
version: 1.7.3
lodash:
specifier: ^4.17.21
version: 4.17.21
naive-ui: naive-ui:
specifier: ^2.39.0 specifier: ^2.39.0
version: 2.39.0(vue@3.4.37(typescript@5.5.4)) version: 2.39.0(vue@3.4.37(typescript@5.5.4))
@@ -21,6 +27,9 @@ importers:
specifier: ^3.4.35 specifier: ^3.4.35
version: 3.4.37(typescript@5.5.4) version: 3.4.37(typescript@5.5.4)
devDependencies: devDependencies:
'@types/lodash':
specifier: ^4.17.7
version: 4.17.7
'@types/node': '@types/node':
specifier: ^22.1.0 specifier: ^22.1.0
version: 22.1.0 version: 22.1.0
@@ -33,6 +42,9 @@ importers:
vite: vite:
specifier: ^5.4.0 specifier: ^5.4.0
version: 5.4.0(@types/node@22.1.0)(sass@1.77.8) version: 5.4.0(@types/node@22.1.0)(sass@1.77.8)
vite-plugin-singlefile:
specifier: ^2.0.2
version: 2.0.2(rollup@4.20.0)(vite@5.4.0(@types/node@22.1.0)(sass@1.77.8))
vue-tsc: vue-tsc:
specifier: ^2.0.29 specifier: ^2.0.29
version: 2.0.29(typescript@5.5.4) version: 2.0.29(typescript@5.5.4)
@@ -387,6 +399,12 @@ packages:
async-validator@4.2.5: async-validator@4.2.5:
resolution: {integrity: sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==} resolution: {integrity: sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==}
asynckit@0.4.0:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
axios@1.7.3:
resolution: {integrity: sha512-Ar7ND9pU99eJ9GpoGQKhKf58GpUOgnzuaB7ueNQ5BMi0p+LZ5oaEnfF999fAArcTIBwXTCHAmGcHOZJaWPq9Nw==}
balanced-match@1.0.2: balanced-match@1.0.2:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
@@ -405,6 +423,10 @@ packages:
resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}
engines: {node: '>= 8.10.0'} engines: {node: '>= 8.10.0'}
combined-stream@1.0.8:
resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
engines: {node: '>= 0.8'}
computeds@0.0.1: computeds@0.0.1:
resolution: {integrity: sha512-7CEBgcMjVmitjYo5q8JTJVra6X5mQ20uTThdK+0kR7UEaDrAWEQcRiBtWJzga4eRpP6afNwwLsX2SET2JhVB1Q==} resolution: {integrity: sha512-7CEBgcMjVmitjYo5q8JTJVra6X5mQ20uTThdK+0kR7UEaDrAWEQcRiBtWJzga4eRpP6afNwwLsX2SET2JhVB1Q==}
@@ -429,6 +451,10 @@ packages:
de-indent@1.0.2: de-indent@1.0.2:
resolution: {integrity: sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg==} resolution: {integrity: sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg==}
delayed-stream@1.0.0:
resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
engines: {node: '>=0.4.0'}
entities@5.0.0: entities@5.0.0:
resolution: {integrity: sha512-BeJFvFRJddxobhvEdm5GqHzRV/X+ACeuw0/BuuxsCh1EUZcAIz8+kYmBp/LrQuloy6K1f3a0M7+IhmZ7QnkISA==} resolution: {integrity: sha512-BeJFvFRJddxobhvEdm5GqHzRV/X+ACeuw0/BuuxsCh1EUZcAIz8+kYmBp/LrQuloy6K1f3a0M7+IhmZ7QnkISA==}
engines: {node: '>=0.12'} engines: {node: '>=0.12'}
@@ -448,6 +474,19 @@ packages:
resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
engines: {node: '>=8'} engines: {node: '>=8'}
follow-redirects@1.15.6:
resolution: {integrity: sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
peerDependenciesMeta:
debug:
optional: true
form-data@4.0.0:
resolution: {integrity: sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==}
engines: {node: '>= 6'}
fsevents@2.3.3: fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -493,6 +532,18 @@ packages:
magic-string@0.30.11: magic-string@0.30.11:
resolution: {integrity: sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A==} resolution: {integrity: sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A==}
micromatch@4.0.7:
resolution: {integrity: sha512-LPP/3KorzCwBxfeUuZmaR6bG2kdeHSbe0P2tY3FLRU4vYrjYz5hI4QZwV0njUx3jeuKe67YukQ1LSPZBKDqO/Q==}
engines: {node: '>=8.6'}
mime-db@1.52.0:
resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}
engines: {node: '>= 0.6'}
mime-types@2.1.35:
resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
engines: {node: '>= 0.6'}
minimatch@9.0.5: minimatch@9.0.5:
resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==} resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}
engines: {node: '>=16 || 14 >=14.17'} engines: {node: '>=16 || 14 >=14.17'}
@@ -528,6 +579,9 @@ packages:
resolution: {integrity: sha512-TesUflQ0WKZqAvg52PWL6kHgLKP6xB6heTOdoYM0Wt2UHyxNa4K25EZZMgKns3BH1RLVbZCREPpLY0rhnNoHVQ==} resolution: {integrity: sha512-TesUflQ0WKZqAvg52PWL6kHgLKP6xB6heTOdoYM0Wt2UHyxNa4K25EZZMgKns3BH1RLVbZCREPpLY0rhnNoHVQ==}
engines: {node: ^10 || ^12 || >=14} engines: {node: ^10 || ^12 || >=14}
proxy-from-env@1.1.0:
resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==}
readdirp@3.6.0: readdirp@3.6.0:
resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==}
engines: {node: '>=8.10.0'} engines: {node: '>=8.10.0'}
@@ -581,6 +635,13 @@ packages:
peerDependencies: peerDependencies:
vue: ^3.0.11 vue: ^3.0.11
vite-plugin-singlefile@2.0.2:
resolution: {integrity: sha512-Z2ou6HcvED5CF0hM+vcFSaFa+klyS8RyyLxW0PbMRLnMbvzTI6ueWyxdYNFhpuXZgz/aj6+E/dHFTdEcw6gb9w==}
engines: {node: '>18.0.0'}
peerDependencies:
rollup: ^4.18.0
vite: ^5.3.1
vite@5.4.0: vite@5.4.0:
resolution: {integrity: sha512-5xokfMX0PIiwCMCMb9ZJcMyh5wbBun0zUzKib+L65vAZ8GY9ePZMXxFrHbr/Kyll2+LSCY7xtERPpxkBDKngwg==} resolution: {integrity: sha512-5xokfMX0PIiwCMCMb9ZJcMyh5wbBun0zUzKib+L65vAZ8GY9ePZMXxFrHbr/Kyll2+LSCY7xtERPpxkBDKngwg==}
engines: {node: ^18.0.0 || >=20.0.0} engines: {node: ^18.0.0 || >=20.0.0}
@@ -902,6 +963,16 @@ snapshots:
async-validator@4.2.5: {} async-validator@4.2.5: {}
asynckit@0.4.0: {}
axios@1.7.3:
dependencies:
follow-redirects: 1.15.6
form-data: 4.0.0
proxy-from-env: 1.1.0
transitivePeerDependencies:
- debug
balanced-match@1.0.2: {} balanced-match@1.0.2: {}
binary-extensions@2.3.0: {} binary-extensions@2.3.0: {}
@@ -926,6 +997,10 @@ snapshots:
optionalDependencies: optionalDependencies:
fsevents: 2.3.3 fsevents: 2.3.3
combined-stream@1.0.8:
dependencies:
delayed-stream: 1.0.0
computeds@0.0.1: {} computeds@0.0.1: {}
css-render@0.15.14: css-render@0.15.14:
@@ -947,6 +1022,8 @@ snapshots:
de-indent@1.0.2: {} de-indent@1.0.2: {}
delayed-stream@1.0.0: {}
entities@5.0.0: {} entities@5.0.0: {}
esbuild@0.21.5: esbuild@0.21.5:
@@ -983,6 +1060,14 @@ snapshots:
dependencies: dependencies:
to-regex-range: 5.0.1 to-regex-range: 5.0.1
follow-redirects@1.15.6: {}
form-data@4.0.0:
dependencies:
asynckit: 0.4.0
combined-stream: 1.0.8
mime-types: 2.1.35
fsevents@2.3.3: fsevents@2.3.3:
optional: true optional: true
@@ -1016,6 +1101,17 @@ snapshots:
dependencies: dependencies:
'@jridgewell/sourcemap-codec': 1.5.0 '@jridgewell/sourcemap-codec': 1.5.0
micromatch@4.0.7:
dependencies:
braces: 3.0.3
picomatch: 2.3.1
mime-db@1.52.0: {}
mime-types@2.1.35:
dependencies:
mime-db: 1.52.0
minimatch@9.0.5: minimatch@9.0.5:
dependencies: dependencies:
brace-expansion: 2.0.1 brace-expansion: 2.0.1
@@ -1061,6 +1157,8 @@ snapshots:
picocolors: 1.0.1 picocolors: 1.0.1
source-map-js: 1.2.0 source-map-js: 1.2.0
proxy-from-env@1.1.0: {}
readdirp@3.6.0: readdirp@3.6.0:
dependencies: dependencies:
picomatch: 2.3.1 picomatch: 2.3.1
@@ -1118,6 +1216,12 @@ snapshots:
evtd: 0.2.4 evtd: 0.2.4
vue: 3.4.37(typescript@5.5.4) vue: 3.4.37(typescript@5.5.4)
vite-plugin-singlefile@2.0.2(rollup@4.20.0)(vite@5.4.0(@types/node@22.1.0)(sass@1.77.8)):
dependencies:
micromatch: 4.0.7
rollup: 4.20.0
vite: 5.4.0(@types/node@22.1.0)(sass@1.77.8)
vite@5.4.0(@types/node@22.1.0)(sass@1.77.8): vite@5.4.0(@types/node@22.1.0)(sass@1.77.8):
dependencies: dependencies:
esbuild: 0.21.5 esbuild: 0.21.5
+242 -45
View File
@@ -1,84 +1,220 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, reactive } from 'vue'; import { h, onMounted, reactive, ref, shallowRef } from 'vue'
import { NIcon, NScrollbar } from 'naive-ui'; import { NIcon, NScrollbar, NDropdown, NQrCode } from 'naive-ui'
import { EyeOffOutline, EyeOutline, CloseOutline, CopyOutline, EllipsisVertical } from '@vicons/ionicons5' import {
import miaoDirectory from './views/miaoDirectory.vue'; EyeOffOutline,
import VirtualPage from './class/virtualPage'; EyeOutline,
import VirtualDirectory from './class/virtualDirectory'; CloseOutline,
CopyOutline,
EllipsisVertical,
QrCodeOutline
} from '@vicons/ionicons5'
import miaoDirectory from './views/miaoDirectory.vue'
import VirtualPage from './class/VirtualPage'
import VirtualDirectory, { VirtualFile } from './class/VirtualDirectory'
import MiaoMask from './components/miaoMask.vue'
import config from './config'
import useVirtualPages from './hooks/useVirtualPages'
const views = reactive<VirtualPage[]>([]) const { baseUrl } = config
const rootDirectory = new VirtualDirectory({ const showModal = ref<boolean>(false)
const modalData = shallowRef<{
component: any
props: any
}>()
const views = useVirtualPages()
const rootDirectory = reactive(
new VirtualDirectory({
name: '根目录', name: '根目录',
stats: { stats: {
atimeMs: 0, atimeMs: 0,
birthtimeMs: 0, birthtimeMs: 0,
ctimeMs: 0, ctimeMs: 0,
mtimeMs: 0, mtimeMs: 0
} }
}) })
)
const createView = (initDirectory: VirtualDirectory, index?: number) => { // component就是一个vue组件,类似于miaoDirectory
const createView = (
component: any,
currentDirectorys?: VirtualDirectory[],
currentFiles?: VirtualFile[],
index?: number
) => {
index ?? (index = views.length) index ?? (index = views.length)
console.log(initDirectory) views.splice(
views.splice(index, 0, reactive<VirtualPage>(new VirtualPage(initDirectory))) index,
0,
reactive<VirtualPage>(new VirtualPage(component, {
directorys: [...(currentDirectorys ?? [])],
files: [...(currentFiles ?? [])]
}))
)
} }
const deleteView = (index: number) => { const deleteView = (index: number) => {
views.splice(index, 1) views.splice(index, 1)
if (views.length === 0) { if (views.length === 0) {
createView(rootDirectory) createView(miaoDirectory, [rootDirectory])
}
}
// 点击标题是隐藏其他标签或显示其他标签,还挺好用的
const handleClickTitle = (index: number) => {
let count = views.filter((v) => v.visible).length
let op = !views[index].visible || count > 1 ? 'hideOthers' : 'showOthers'
let _index = 0
while (_index < views.length) {
if (_index !== index) {
views[_index].visible = op === 'hideOthers' ? false : true
} else {
views[_index].visible = true
}
_index += 1
}
}
// 顶部菜单相关
function renderIcon(icon: any) {
return () => {
return h(NIcon, null, {
default: () => h(icon)
})
}
}
const openMenuOption = [
{
label: '分享',
key: 'share',
icon: renderIcon(QrCodeOutline)
}
]
const handleMenuSelect = (key: string) => {
if (key === 'share') {
showModal.value = true
modalData.value = {
component: NQrCode,
props: {
value: baseUrl,
size: 300,
errorCorrectionLevel: 'H'
}
}
} }
} }
onMounted(() => { onMounted(() => {
createView(rootDirectory) createView(miaoDirectory, [rootDirectory])
}) })
// todo: 让所有伪页面共享一个rootDirectory
</script> </script>
<template> <template>
<div class="view">
<div class="view-controler"> <div class="view-controler">
<n-scrollbar x-scrollable> <n-scrollbar x-scrollable>
<div class="tags-container"> <div class="tags-container">
<div class="tag" v-for="(view, index) of views" :key="view.uid"> <transition-group name="tab">
<div class="tag-title">{{ view.title }}</div> <div
<div class="tag-point" :style="{ backgroundColor: view.color } "></div> class="tab"
<div class="tag-control"> v-for="(view, index) of views"
<n-icon class="tag-control-icon icon" @click="view.switchShow()"> :key="view.uid">
<EyeOutline v-show="view.visible" class="icon-inner" /> <div
<EyeOffOutline v-show="!view.visible" class="icon-inner" /> class="tab-title"
@click="handleClickTitle(index)">
{{ view.title }}
</div>
<div
class="tab-point"
:style="{ backgroundColor: view.color }"></div>
<div class="tab-control">
<n-icon
class="tag-control-icon icon"
@click="view.switchShow()">
<EyeOutline
v-show="view.visible"
class="icon-inner" />
<EyeOffOutline
v-show="!view.visible"
class="icon-inner" />
</n-icon> </n-icon>
<n-icon class="tag-control-icon icon" @click="createView(view.currentDirectory, index + 1)"> <n-icon
class="tag-control-icon icon"
@click="
createView(
view.component,
view.currentDirectorys,
view.currentFiles,
index + 1
)
">
<CopyOutline /> <CopyOutline />
</n-icon> </n-icon>
<n-icon class="tag-control-icon icon" @click="deleteView(index)"> <n-icon
class="tag-control-icon icon"
@click="deleteView(index)">
<CloseOutline class="icon-inner" /> <CloseOutline class="icon-inner" />
</n-icon> </n-icon>
</div> </div>
</div> </div>
</transition-group>
</div> </div>
</n-scrollbar> </n-scrollbar>
<div class="view-controler-menu"> <div class="view-controller-menu">
<div class="view-controler-menu-item"> <div class="view-controller-menu-item">
<n-icon class="icon" @click=""> <n-dropdown
trigger="click"
:options="openMenuOption"
@select="handleMenuSelect">
<n-icon class="icon">
<EllipsisVertical class="icon-inner" /> <EllipsisVertical class="icon-inner" />
</n-icon> </n-icon>
</n-dropdown>
</div> </div>
</div> </div>
</div> </div>
<div class="view-container"> <div class="view-container">
<div class="view" v-for="(view, index) of views" v-show="view.visible" :key="view.uid"> <transition-group name="page">
<miao-directory v-model:current-directory="view.currentDirectory" :color="view.color" :index="index" @exit="deleteView(index)"></miao-directory> <div
class="view-container-item"
v-for="(view, index) of views"
v-show="view.visible"
:key="view.uid">
<component
:is="view.component"
v-model:current-objects="view.currentDirectorys"
:id="view.uid"
:color="view.color"
@exit="deleteView(index)"></component>
</div>
</transition-group>
</div> </div>
</div> </div>
<!-- 模态框展示,用来显示分享二维码,设置菜单之类的东西 -->
<MiaoMask v-model:show="showModal" @click="showModal = false">
<component
@click="(e:any) => e.stopPropagation()"
:is="modalData?.component"
v-bind="modalData?.props"></component>
</MiaoMask>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
$controler-height: 25px; $controler-height: 25px;
$tag-width: 170px;
.view-controler { .view {
position: relative;
height: 100%;
width: 100%;
.view-controler {
display: flex; display: flex;
height: $controler-height; height: $controler-height;
width: 100%; width: 100%;
@@ -89,43 +225,45 @@ $controler-height: 25px;
display: flex; display: flex;
margin-left: 5px; margin-left: 5px;
flex: 1; flex: 1;
// overflow-x: scroll; // overflow-x: scroll;
.tag { .tab {
position: relative; position: relative;
width: 170px; width: $tag-width;
margin: 0 5px; margin: 0 5px;
// flex: 1; // flex: 1;
display: flex; display: flex;
border-radius: 5px 5px 0 0; border-radius: 5px 5px 0 0;
align-items: center; align-items: center;
.tag-title { .tab-title {
margin-left: 4px; margin-left: 4px;
// width: 70%; // width: 70%;
user-select: none; user-select: none;
cursor: pointer;
} }
.tag-point { .tab-point {
height: 5px; height: 5px;
aspect-ratio: 1; aspect-ratio: 1;
border-radius: 66px; border-radius: 66px;
margin-left: 5px; margin-left: 5px;
} }
.tag-control { .tab-control {
position: absolute; position: absolute;
right: 10px; right: 10px;
display: flex; display: flex;
align-items: center; align-items: center;
.tag-control-icon:not(:last-child) { .tab-control-icon:not(:last-child) {
margin-right: 5px; margin-right: 5px;
} }
} }
&:not(:last-child)::after { &:not(:last-child)::after {
content: ''; content: '';
height: calc($controler-height*0.6); height: calc($controler-height * 0.6);
width: 1px; width: 1px;
border-right: 1px solid black; border-right: 1px solid black;
position: absolute; position: absolute;
@@ -134,21 +272,23 @@ $controler-height: 25px;
} }
} }
.view-controler-menu { .view-controller-menu {
position: relative; position: relative;
display: flex; display: flex;
align-items: center; align-items: center;
padding: 0 5px; padding: 0 5px;
.view-controler-menu-item {
.view-controller-menu-item {
height: 100%; height: 100%;
aspect-ratio: 1; aspect-ratio: 1;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
} }
&::before { &::before {
content: ''; content: '';
height: calc($controler-height*0.6); height: calc($controler-height * 0.6);
width: 1px; width: 1px;
border-right: 1px solid black; border-right: 1px solid black;
position: absolute; position: absolute;
@@ -171,36 +311,93 @@ $controler-height: 25px;
background-color: rgba(128, 128, 128, 0.4); background-color: rgba(128, 128, 128, 0.4);
} }
} }
} }
.view-container { .view-container {
position: relative; position: relative;
display: flex; display: flex;
// flex-direction: column; // flex-direction: column;
height: calc(100% - $controler-height); height: calc(100% - $controler-height);
overflow-y: overlay; overflow-y: overlay;
overflow-x: overlay; overflow-x: overlay;
.view {
.view-container-item {
flex: 1; flex: 1;
height: 100%; height: 100%;
} }
&::-webkit-scrollbar { &::-webkit-scrollbar {
position: absolute; position: absolute;
width: 4px; width: 4px;
} }
// 滚动条轨道 // 滚动条轨道
&::-webkit-scrollbar-track { &::-webkit-scrollbar-track {
// background: rgb(239, 239, 239); // background: rgb(239, 239, 239);
border-radius: 2px; border-radius: 2px;
} }
// 小滑块 // 小滑块
&::-webkit-scrollbar-thumb { &::-webkit-scrollbar-thumb {
background: #e0e0e0; background: #e0e0e0;
// border-radius: 5px; // border-radius: 5px;
} }
&::-webkit-scrollbar-thumb:hover { &::-webkit-scrollbar-thumb:hover {
background: #999999; background: #999999;
} }
}
}
// transition动画相关
.view {
.view-controler {
.tags-container {
.tab-move,
.tab-enter-active {
transition: all 0.2s ease;
}
.tab-leave-active {
transition: none;
}
.tab-enter-from {
opacity: 0;
transform: translateY(-30px);
}
// .tab-leave-to {
// opacity: 0;
// transform: translateY(-80px) translateX(calc($tag-width + 10px));
// }
.tab-leave-active {
position: absolute;
}
}
}
// .view-container {
// .page-move {
// transition: all 0.2s ease;
// }
// .page-enter-active {
// }
// .page-leave-active {
// transition: none;
// }
// .page-enter-from {
// opacity: 0;
// }
// .page-leave-active {
// position: absolute;
// }
// }
} }
</style> </style>
+165
View File
@@ -0,0 +1,165 @@
import generateId from "@/hooks/generateId";
import useMiaoFetchApi from "@/hooks/useMiaoFetchApi";
import VirtualDirectory from "./VirtualDirectory";
const miaoFetchApi = useMiaoFetchApi();
export class UploadQueueItem {
constructor(
file: File,
targetDirectory: VirtualDirectory,
config?: {
onSuccess?: () => void;
onFailed?: () => void;
}
) {
this.file = file;
this.targetDirectory = targetDirectory;
this.uid = generateId();
this.status = "waiting";
this.process = 0;
this.onSuccess = config && config.onSuccess;
this.onFailed = config && config.onFailed;
}
uid: number;
file: File;
targetDirectory: VirtualDirectory;
status: "waiting" | "uploading" | "success" | "failed";
process: number;
failedReason: unknown | undefined;
onSuccess?: () => void;
onFailed?: () => void;
_abort: (() => void | undefined) | undefined;
_status: Promise<any> | undefined;
/**
* 开始上传文件
*/
startUpload() {
if (this.status === "uploading") {
return;
}
const { abort, response } = miaoFetchApi.upload(this.file, this.targetDirectory, {
onProcess: percent => {
this.process = percent;
}
});
this._abort = abort;
this._status = response;
this.status = "uploading";
response
.then(() => {
this.status = "success";
this.onSuccess && this.onSuccess();
this._abort = undefined;
this._status = undefined;
})
.catch(e => {
this.status = "failed";
this.failedReason = e;
this.onFailed && this.onFailed();
});
}
/**
* 终止上传文件
*/
abortUpload() {
this._abort && this._abort();
this.status = "failed";
this.failedReason = "abort";
}
}
export default class UploadQueue {
constructor() {
this.uid = generateId();
this.queue = [];
this.mode = "serial";
}
uid: number;
queue: UploadQueueItem[];
current: UploadQueueItem | undefined;
// 未来再去实现,目前就是串行的
// 好像也不用去实现
mode: "serial" | "parallel";
get status() {
for (let item of this.queue) {
if (item.status === "uploading") {
return "busy";
}
}
return "free";
}
/**
* 获取下一个需要被上传的item
*/
get nextUplpadItem() {
for (let item of this.queue) {
if (item.status === "waiting") {
return item;
}
}
}
/**
* 开始串行的上传循环
*/
loop() {
if (this.status === "busy") {
return;
}
if (this.nextUplpadItem) {
this.nextUplpadItem.startUpload();
}
}
/**
* 向上传文件队列输送一批新的文件
* @param {any} files 需要上传的文件
* @param {any} targetDirectory 目标文件夹
* @param {any} option 每个文件上传完成以后都会触发一遍的回调函数
* @returns {any}
*/
push(
files: File[],
targetDirectory: VirtualDirectory,
option?: {
/**
* 每个文件上传完成以后都会触发一遍的回调函数
*/
onFinish?: () => void;
/**
* 是否立即开始上传,若否则按队列顺序一个一个上传
*/
immediately?: boolean;
}
) {
const onFinish = option?.onFinish;
const immediately = option?.immediately ?? false;
const uploadQueue = files.map(file => {
return new UploadQueueItem(file, targetDirectory, {
onSuccess: () => {
this.loop();
onFinish && onFinish();
},
onFailed: () => {
this.loop();
}
});
});
this.queue.push(...uploadQueue);
if (!immediately) {
this.loop();
} else {
uploadQueue.forEach(item => {
item.startUpload();
});
}
return uploadQueue;
}
}
@@ -1,6 +1,10 @@
import generateId from "@/hooks/generateId"; import generateId from "@/hooks/generateId";
import useMiaoFetchApi from "@/hooks/useMiaoFetchApi";
// import { debounce } from "lodash";
import type { stats, file, directory } from "@/types/type.ts"; import type { stats, file, directory } from "@/types/type.ts";
const miaoFetchApi = useMiaoFetchApi();
export class VirtualFile { export class VirtualFile {
constructor(info: file, parent: VirtualDirectory) { constructor(info: file, parent: VirtualDirectory) {
this.name = info.name; this.name = info.name;
@@ -68,11 +72,11 @@ class VirtualDirectory {
* 获取从根目录开始的按顺序的文件夹 * 获取从根目录开始的按顺序的文件夹
* @returns {VirtualDirectory[]} * @returns {VirtualDirectory[]}
*/ */
get directoryArray(): VirtualDirectory[] { get getParents(): VirtualDirectory[] {
if (!this.parent) { if (!this.parent) {
return [this]; return [this];
} }
return [...this.parent.directoryArray, this]; return [...this.parent.getParents, this];
} }
/** /**
@@ -127,5 +131,14 @@ class VirtualDirectory {
return this.files?.includes(item) ?? false; return this.files?.includes(item) ?? false;
} }
} }
/**
* 调用后重新向远端拉取文件夹信息并进行更新
* @returns {void}
*/
async update(): Promise<void> {
const data: (file | directory)[] = await miaoFetchApi.get(this);
this.updateContent(data);
}
} }
export default VirtualDirectory; export default VirtualDirectory;
+63
View File
@@ -0,0 +1,63 @@
import { shallowRef } from "vue";
import VirtualDirectory, { VirtualFile } from "./VirtualDirectory";
import generateId from "@/hooks/generateId";
const getRandomWebSafeColor = (() => {
const webSafeColors = ["#009900", "#999900", "#009999", "#990099", "#0000ee"];
let counter = 0;
return () => {
const color = webSafeColors[counter % webSafeColors.length];
counter += 1;
return color;
};
})();
export default class VirtualPage {
constructor(component: any, initObjects?:{ directorys?: VirtualDirectory[], files?: VirtualFile[]}) {
this.component = shallowRef(component);
this.currentDirectorys = initObjects?.directorys ?? [];
this.currentFiles = initObjects?.files ?? [];
this.visible = true;
this.uid = generateId();
this.refreshKey = Math.random();
this.color = getRandomWebSafeColor();
}
// 页面使用的组件
component: any;
// 是否可见
visible: boolean;
// 当前正在使用的文件夹
currentDirectorys: VirtualDirectory[];
// 当前正在使用的文件
currentFiles: VirtualFile[];
// 区分每一个页面的唯一id
uid: number;
// 当refreshKey改变时需要刷新页面,目前还没接入刷新
refreshKey: number;
// 为了区分,每个虚拟页面都会分配一个color,这个color会体现在tab上
color: string;
// 用于展示的title
_title?: string;
get title() {
if (this._title) {
return this._title;
}
return this.currentDirectorys[0].name;
}
setTitle(title: string) {
this._title = title;
}
// 切换显示状态
switchShow() {
this.visible = !this.visible;
}
// 刷新,不过好像没有用得到的时候吧
// 事实上也不应该用得到,因为更新应该是响应式的
refresh() {
this.refreshKey = Math.random();
}
}
-48
View File
@@ -1,48 +0,0 @@
import VirtualDirectory from "./virtualDirectory";
import generateId from "@/hooks/generateId";
const getRandomWebSafeColor = (() => {
const webSafeColors = ["#009900", "#999900", "#009999", "#990099", "#0000ee"];
let counter = 0
return () => {
const color = webSafeColors[counter % webSafeColors.length]
counter += 1
return color;
};
})();
export default class VirtualPage {
constructor(initDirectory: VirtualDirectory) {
this.visible = true;
this.uid = generateId();
this.currentDirectory = initDirectory;
this.refreshKey = Math.random();
this.color = getRandomWebSafeColor();
}
visible: boolean;
currentDirectory: VirtualDirectory;
// 区分每一个页面的唯一id
uid: number;
// 当refreshKey改变时需要刷新页面,目前还没接入刷新
refreshKey: number;
color: string;
get title() {
return this.currentDirectory.name;
}
// 切换显示状态
switchShow() {
this.visible = !this.visible;
}
// 设置(同步)正在展示的文件夹
setCurrrentDirectory(currDir: VirtualDirectory) {
this.currentDirectory = currDir;
}
refresh() {
this.refreshKey = Math.random();
}
}
+89
View File
@@ -0,0 +1,89 @@
<!-- 基于naiveui的下拉菜单实现的自定义下拉菜单 -->
<!-- 支持长按和右键呼出下拉菜单 -->
<template>
<div class="main" @contextmenu="handleContextMenu" @mouseleave="handleMainMouseLeave" @touchstart="handleTouchStart"
@touchend="handleTouchEnd">
<slot></slot>
</div>
<n-dropdown placement="bottom-start" trigger="manual" :x="x" :y="y" :options="props.options"
:show="showContextMenu > 0" :on-clickoutside="onClickoutside" @select="handleSelect" @mouseleave="
showContextMenu -= 1" @mouseenter="showContextMenu += 1" />
</template>
<script setup lang="ts">
import { NDropdown } from 'naive-ui/es/dropdown';
import { DropdownOption } from 'naive-ui/es/dropdown';
import { nextTick, ref } from 'vue';
const props = defineProps<{
options: DropdownOption[]
// 长按呼出右键菜单的时延,undefined时不生效
touchTimeOut?: number
}>()
const emit = defineEmits<{
select: [key: string]
}>()
const x = ref(0)
const y = ref(0)
const showContextMenu = ref(0)
// 长按计时器
let timer_touch: string | number | NodeJS.Timeout | undefined
const onClickoutside = async () => {
showContextMenu.value = 0
}
const handleMainMouseLeave = async () => {
setTimeout(() => {
showContextMenu.value -= 1
}, 20)
// nextTick(()=>{
// showContextMenu.value -= 1
// })
}
const handleSelect = async (key: string) => {
emit('select', key)
showContextMenu.value = 0
}
const handleContextMenu = (e: MouseEvent) => {
e.preventDefault()
showContextMenu.value = 0
nextTick().then(() => {
showContextMenu.value += 1
x.value = e.clientX
y.value = e.clientY
})
}
const handleTouchStart = (e: TouchEvent) => {
if(props.touchTimeOut === undefined) {
return
}
timer_touch ?? clearTimeout(timer_touch)
timer_touch = setTimeout(() => {
showContextMenu.value = 1
x.value = e.targetTouches[0].clientX
y.value = e.targetTouches[0].clientY
}, props.touchTimeOut)
}
const handleTouchEnd = () => {
if(timer_touch) {
clearTimeout(timer_touch)
timer_touch = undefined
}
}
</script>
<style>
.main {
width: 100%;
height: 100%;
position: relative;
}
</style>
@@ -1,122 +1,225 @@
<template> <template>
<div class="miao-item" draggable="true" ref="itemRef" @dragstart="handleDragStart"> <div class="miao-item" draggable="true" ref="itemRef" @dragstart="handleDragStart">
<div class="item-main"> <miaoContextMenu :options="dropDownOptions" :touch-time-out="500" @select="handleDropdownSelect">
<div class="item-main" :class="props.selected ? 'item-main-selected' : ''" ref="mainRef">
<div class="item-main-front" :style="{ backgroundColor: props.color }"></div> <div class="item-main-front" :style="{ backgroundColor: props.color }"></div>
<Icon class="item-main-icon"></Icon> <Icon class="item-main-icon" v-show="clientWidth > 250"></Icon>
<div class="item-main-info"> <div class="item-main-info">
<div class="item-main-info-name"> <div class="item-main-info-name">
{{ name }} <Icon class="item-main-info-name-icon" v-show="clientWidth <= 250"></Icon>
<n-ellipsis style="max-width: 140px;">{{ name }}</n-ellipsis>
</div> </div>
<div class="item-main-info-date" v-if="time"> <div class="item-main-info-date" v-if="time">
{{ time }} {{ time }}
</div> </div>
</div> </div>
<n-dropdown trigger="click" :options="dropDownOptions" @select="handleDropdownSelect"> <!-- 菜单现在通过右键/长按呼出 -->
<div class="item-main-option" @click="e=>e.stopPropagation()"> <!-- <n-dropdown trigger="click" :options="dropDownOptions" @select="handleDropdownSelect">
<div class="item-main-option" @click="(e) => e.stopPropagation()">
<EllipsisVertical class="item-main-option-icon" /> <EllipsisVertical class="item-main-option-icon" />
</div> </div>
</n-dropdown> </n-dropdown> -->
</div> </div>
</miaoContextMenu>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import VirtualDirectory, { VirtualFile } from '@/class/VirtualDirectory'
import miaoContextMenu from '../miaoContextMenu.vue'
import {
DocumentText,
FileTray,
Help,
Image,
LogoChrome,
LogoCss3,
LogoJavascript,
LogoVue,
PlayCircle,
Disc
} from '@vicons/ionicons5'
import { computed, onMounted, ref } from 'vue'
import dateFormatter from '@/hooks/dateFormatter'
import { NEllipsis } from 'naive-ui'
// import useMiaoFetchApi from '@/hooks/useMiaoFetchApi'
import VirtualDirectory, { VirtualFile } from '@/class/virtualDirectory'; // const miaoFetchApi = useMiaoFetchApi()
import { DocumentText, FileTray, Help, Image, LogoChrome, LogoCss3, LogoJavascript, LogoVue, PlayCircle, EllipsisVertical, Disc } from '@vicons/ionicons5';
import { computed, ref } from 'vue';
import dateFormatter from '@/hooks/dateFormatter';
import useDataBus from '@/hooks/useDataBus';
import { NDropdown } from 'naive-ui';
const dataBus = useDataBus()
const emit = defineEmits<{
download: []
}>()
const props = defineProps<{ const props = defineProps<{
item: VirtualDirectory | VirtualFile item: VirtualDirectory | VirtualFile
name?: string name?: string
color:string color: string
selected: boolean
}>()
const emit = defineEmits<{
download: []
delete: []
rename: []
dragStart: [event: DragEvent, item: VirtualDirectory | VirtualFile]
onSelected: []
}>() }>()
const itemType = ref<'file' | 'directory'>(props.item.type) const itemType = ref<'file' | 'directory'>(props.item.type)
const mainRef = ref<HTMLDivElement>()
// 使用ResizeObserver实现
const clientWidth = ref<number>(666)
const name = props.name ?? props.item.name const name = props.name ?? props.item.name
const time = computed(()=>{ const time = computed(() => {
return dateFormatter(new Date(props.item.stats.mtimeMs), "yyyy-MM-dd hh:mm:ss"); return dateFormatter(
new Date(props.item.stats.mtimeMs),
'yyyy-MM-dd hh:mm:ss'
)
}) })
const dropDownOptions = computed(()=> { const dropDownOptions = computed(() => {
const options = [] const options = [
if(itemType.value === 'file'){ {
options.push(...[{ label: '重命名',
key: 'rename'
},
{
label: '删除',
key: 'delete'
},
]
if (itemType.value === 'file') {
options.push(
...[
{
label: '下载', label: '下载',
key: 'download', key: 'download'
} }
]) ]
)
}
if (props.selected === false) {
options.push(
...[
{
label: '多选:选择',
key: 'select'
}
]
)
} else {
options.push(
...[
{
label: '多选:取消',
key: 'select'
}
]
)
} }
return options return options
}) })
const handleDropdownSelect = (key: 'download') => { // 是不是可以直接在这里面实现?
console.log(key) const handleDropdownSelect = (key: string) => {
emit(key) if (key === 'rename') {
emit('rename')
} else if (key === 'download') {
emit('download')
} else if (key === 'delete') {
emit('delete')
} else if (key === 'select') {
emit('onSelected')
}
} }
const Icon = computed(()=>{ const Icon = computed(() => {
try{ try {
if(props.item.type === 'directory') { if (props.item.type === 'directory') {
return FileTray return FileTray
} else if(props.item.type === 'file') { } else if (props.item.type === 'file') {
const aft = props.item.name.split('.').at(-1)?.toLowerCase() const aft = props.item.name.split('.').at(-1)?.toLowerCase()
if(!aft){ if (!aft) {
throw(1) throw 1
}else if(['txt', 'doc', 'docs', 'docx', 'xls', 'xlsx'].includes(aft)){ } else if (
['txt', 'doc', 'docs', 'docx', 'xls', 'xlsx'].includes(aft)
) {
return DocumentText return DocumentText
}else if(['mp3', 'wav', 'ape', 'acc', 'ogg', 'flac'].includes(aft)){ } else if (
['mp3', 'wav', 'ape', 'acc', 'ogg', 'flac'].includes(aft)
) {
return Disc return Disc
}else if(['.xbm','.tif','pjp','.svgz','jpg','jpeg','ico','tiff','.gif','svg','.jfif','.webp','.png','.bmp','pjpeg','.avif'].includes(aft)){ } else if (
[
'.xbm',
'.tif',
'pjp',
'.svgz',
'jpg',
'jpeg',
'ico',
'tiff',
'.gif',
'svg',
'.jfif',
'.webp',
'.png',
'.bmp',
'pjpeg',
'.avif'
].includes(aft)
) {
return Image return Image
}else if(['mp4', 'm2v', 'mkv'].includes(aft)){ } else if (['mp4', 'm2v', 'mkv'].includes(aft)) {
return PlayCircle return PlayCircle
}else if(['js', 'jsx', 'ts', 'tsx'].includes(aft)){ } else if (['js', 'jsx', 'ts', 'tsx'].includes(aft)) {
return LogoJavascript return LogoJavascript
}else if(['html'].includes(aft)){ } else if (['html'].includes(aft)) {
return LogoChrome return LogoChrome
}else if(['css', 'scss', 'less'].includes(aft)){ } else if (['css', 'scss', 'less'].includes(aft)) {
return LogoCss3 return LogoCss3
}else if(['vue'].includes(aft)){ } else if (['vue'].includes(aft)) {
return LogoVue return LogoVue
} }
return DocumentText return DocumentText
} }
}catch{ } catch {
return Help return Help
} }
}) })
const itemRef = ref() const itemRef = ref()
const handleDragStart = () => { const handleDragStart = (event: DragEvent) => {
dataBus.set('dragData', [ props.item ]) emit('dragStart', event, props.item)
// dataBus.set('dragData', [props.item])
} }
onMounted(() => {
const observer = new ResizeObserver(entries => {
for (let entry of entries) {
clientWidth.value = entry.contentRect.width;
}
});
if (mainRef.value) {
observer.observe(mainRef.value);
}
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.miao-item { .miao-item {
cursor: pointer; cursor: pointer;
width: calc(100% - 16px); width: calc(100% - 20px);
min-width: 250px; min-width: 170px;
// aspect-ratio: 66/9; // aspect-ratio: 66/9;
height: 50px; height: 50px;
position: relative; position: relative;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
margin: 10px 8px; margin: 10px 10px;
.item-main { .item-main {
position: relative; position: relative;
width: 100%; width: 100%;
@@ -125,30 +228,49 @@ const handleDragStart = () => {
border-radius: 7px; border-radius: 7px;
display: flex; display: flex;
align-items: center; align-items: center;
transition: background-color 0.3s; transition: background-color 0.3s ease;
.item-main-front { .item-main-front {
height: 100%; height: 100%;
width: 10px; width: 10px;
border-radius: 7px 0 0 7px ; border-radius: 7px 0 0 7px;
background-color: rgb(0, 0, 0); background-color: rgb(0, 0, 0);
} }
.item-main-icon { .item-main-icon {
margin-left: 10px; margin-left: 10px;
height: 80%; height: 80%;
color: #00403e;
transition: color 0.15s ease-out;
} }
.item-main-info { .item-main-info {
margin-left: 10px; margin-left: 10px;
height: 100%; height: 100%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
&-name { &-name {
position: relative;
user-select: none; user-select: none;
display: flex;
align-items: center;
margin-top: 3px;
&-icon {
color: #00403e;
width: 20px;
margin-right: 5px;
transition: color 0.15s ease-out;
} }
}
&-date { &-date {
user-select: none; user-select: none;
font-size: small; font-size: small;
} }
} }
.item-main-option { .item-main-option {
height: 100%; height: 100%;
width: 20px; width: 20px;
@@ -162,21 +284,32 @@ const handleDragStart = () => {
align-items: center; align-items: center;
transition: background-color 0.3s; transition: background-color 0.3s;
.item-main-option-icon { .item-main-option-icon {
color: #000; color: #000;
transition: color 0.15s; transition: color 0.15s;
} }
&:hover, &:active {
&:hover,
&:active {
background-color: #8b8b8b; background-color: #8b8b8b;
.item-main-option-icon { .item-main-option-icon {
color: #FFF; color: #fff;
} }
} }
} }
&:hover, &:active {
background-color: #d2d2d2;
}
&:hover,
&:active {
background-color: #d2d2d2;
}
}
.item-main-selected {
background-color: rgba(0, 128, 207, 0.32);
&:hover {
background-color: rgba(0, 128, 207, 0.64);;
}
} }
} }
</style> </style>
+106
View File
@@ -0,0 +1,106 @@
<template>
<div
class="container"
@dragover="handleDragOver"
@dragleave="handleDragLeave"
@drop="handleDrop">
<slot></slot>
<miao-mask v-model:show="showMask"></miao-mask>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import miaoMask from './miaoMask.vue'
import VirtualDirectory, { VirtualFile } from '@/class/VirtualDirectory'
import config from '@/config'
import useDataBus from '@/hooks/useDataBus'
const dataBus = useDataBus()
const { uploadSizeLimit } = config
const emit = defineEmits<{
onFiles: [files: File[]]
onVirtualFiles: [vFiles: VirtualFile[]]
onVirtualDirectory: [vDirectory: VirtualDirectory[]]
}>()
const showMask = ref<number>(0)
// File類型的數據可能爲文件夾,通過FileReader進行判斷
const isFile = (file: File) =>
new Promise((resolve) => {
const reader = new FileReader()
reader.onload = () => {
resolve(true)
reader.abort()
}
reader.onerror = () => {
resolve(false)
reader.abort()
}
reader.readAsText(file)
})
/**
* 只保留文件,移去文件夹
* @param {File[]} files
*/
const removeDirectory = async (files: File[]) => {
let index = 0
while (index < files.length) {
const currentFile = files[index]
const _isFile = await isFile(currentFile)
if (_isFile) {
index += 1
continue
} else {
files.splice(index, 1)
continue
}
}
}
const handleDragOver = async (event: DragEvent) => {
showMask.value += 1
event.preventDefault()
}
const handleDragLeave = async () => {
showMask.value = 0
}
const handleDrop = async (event: DragEvent) => {
showMask.value = 0
event.preventDefault()
event.stopPropagation()
// todo: uploadSize的限制不應該在這裏
const files = [...(event.dataTransfer?.files ?? [])].filter(
(file) => file.size < uploadSizeLimit
)
await removeDirectory(files)
const virtualFiles: VirtualFile[] = dataBus.pop('dragData_vFiles')
const virtualDirectory: VirtualDirectory[] = dataBus.pop(
'dragData_vDirectory'
)
// console.log({ virtualDirectory, virtualFiles })
if (files && files.length) {
emit('onFiles', files)
}
if (virtualFiles && virtualFiles.length) {
emit('onVirtualFiles', virtualFiles)
}
if (virtualDirectory && virtualDirectory.length) {
emit('onVirtualDirectory', virtualDirectory)
}
}
</script>
<style lang="scss" scoped>
.container {
width: 100%;
height: 100%;
position: relative;
}
</style>
+9 -2
View File
@@ -1,7 +1,7 @@
<template> <template>
<transition name="transition"> <transition name="transition">
<div class="mask-body" ref="maskBodyRef" v-show="showMask"> <div class="mask-body" ref="maskBodyRef" v-show="showMask">
<slot> {{}} </slot> <slot></slot>
</div> </div>
</transition> </transition>
</template> </template>
@@ -18,24 +18,31 @@ const showMask = defineModel<boolean | number>('show', { default: false, require
height: 100%; height: 100%;
width: 100%; width: 100%;
position: absolute; position: absolute;
top:0; top: 0;
left: 0; left: 0;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
background-color: rgba(0, 0, 0, 0.3); background-color: rgba(0, 0, 0, 0.3);
z-index: 7058214053994319; z-index: 7058214053994319;
// &-container {
// }
&-show { &-show {
display: flex; display: flex;
transition: opacity 0.3s 0.01s; transition: opacity 0.3s 0.01s;
opacity: 1; opacity: 1;
} }
&-hide { &-hide {
opacity: 0; opacity: 0;
transition: display 0.01s 0.3s; transition: display 0.01s 0.3s;
display: none; display: none;
} }
} }
.transition-enter-active, .transition-enter-active,
.transition-leave-active { .transition-leave-active {
transition: opacity 0.3s ease; transition: opacity 0.3s ease;
+83
View File
@@ -0,0 +1,83 @@
<template>
<miao-mask v-model:show="showMask">
<n-card class="popup-card" :title="popupConfig?.title" size="medium">
{{ popupConfig?.content }}
<n-input class="popup-input" v-model:value="inputValue" type="text" v-bind="popupConfig?.inputProps"
v-if="popupConfig?.inputProps" />
<div class="popup-button-container">
<n-button class="popup-button-container-button" v-for="option in popupConfig?.options" :key="option.label"
:type="option.type" @click="_resolve && _resolve(option.key)">{{ option.label }}</n-button>
</div>
</n-card>
</miao-mask>
</template>
<script lang="ts" setup>
import { ref, nextTick } from "vue";
import { NCard, NInput, NButton } from "naive-ui";
import miaoMask from "./miaoMask.vue";
import { InputProps } from "naive-ui";
const showMask = ref(false);
const inputValue = ref<string>("");
const _resolve = ref()
type popupConfigType = {
title: string
content?: string
inputValue?: string,
inputProps?: InputProps
options: {
label: string
key: unknown
type: 'default' | 'tertiary' | 'primary' | 'success' | 'info' | 'warning' | 'error'
}[]
}
const popupConfig = ref<popupConfigType>()
const popup = async (config: popupConfigType) => {
popupConfig.value = config
inputValue.value = config.inputValue ?? ''
showMask.value = true
const key = await new Promise((resolve: (key: unknown) => unknown) => {
_resolve.value = resolve
})
const text = inputValue.value
showMask.value = false;
nextTick(() => {
inputValue.value = ''
_resolve.value = undefined
})
return {
text,
key
};
};
defineExpose({ popup });
</script>
<style scoped lang="scss">
.popup-card {
width: 80%;
.popup-input {
margin-bottom: 10px;
}
.popup-button-container {
height: 100%;
width: 100%;
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
.popup-button-container-button {
margin-top: 3px;
&:not(:last-child) {
margin-right: 5px;
}
}
}
}
</style>
+10 -3
View File
@@ -4,6 +4,13 @@ export default {
baseUrl, baseUrl,
uploadSizeLimit: 1024 * 1024 * 100, uploadSizeLimit: 1024 * 1024 * 100,
api: { api: {
get: '/get' get: '/get',
} upload: '/upload',
}; delete: '/delete',
query: '/query',
rename: '/rename',
mkdir: '/mkdir',
cut: '/cut'
},
enableUpload: true
}
+47
View File
@@ -0,0 +1,47 @@
export const filePicker = (() => {
let _resolve: ((files: File[]) => void) | undefined;
return (option?: { accept?: "string"; multiple: boolean }) => {
if (_resolve) {
_resolve([]);
_resolve = undefined;
}
return new Promise<File[]>(resolve => {
const inpEle = document.createElement("input");
inpEle.id = `__file_${Math.ceil(Math.random() * 100000000)}`;
inpEle.type = "file";
inpEle.style.display = "none";
_resolve = resolve;
// 文件类型限制
// inpEle.accept="image/*"
option?.accept && (inpEle.accept = option?.accept);
// 多选限制
option?.multiple && (inpEle.multiple = option?.multiple);
// inpEle.addEventListener("change", event => fn.call(inpEle, event, inpEle.files), { once: true });
inpEle.addEventListener(
"change",
() => {
if (!inpEle.files) {
return;
}
const files: File[] = [];
let i = 0;
while (i < inpEle.files?.length) {
const _file = inpEle?.files?.item(i);
if (_file !== null) {
files.push(_file);
}
i += 1;
}
resolve(files);
_resolve = undefined
},
{ once: true }
);
inpEle.click();
});
};
})();
export default {
filePicker
};
+9 -2
View File
@@ -1,12 +1,19 @@
const dataStorage: any = {}; import { reactive } from "vue";
let dataStorage: {
[key: string | number] : any
};
export default function useDataBus() { export default function useDataBus() {
if(dataStorage === undefined) {
dataStorage = reactive({})
}
return { return {
set(key: string | number, value: any) { set(key: string | number, value: any) {
dataStorage[key] = value; dataStorage[key] = value;
return value; return value;
}, },
get(key: string | number) { pop(key: string | number) {
const value = dataStorage[key]; const value = dataStorage[key];
dataStorage[key] = undefined; dataStorage[key] = undefined;
return value; return value;
-22
View File
@@ -1,22 +0,0 @@
type miaoFetchConfig = {
retry: number;
};
export default function useMiaoFetch(config: miaoFetchConfig) {
const { retry } = config;
return async (input: RequestInfo | URL, init?: RequestInit) => {
let retryTimes = 0;
let err: any;
while (retryTimes <= retry) {
try {
const response = await fetch(input, init);
return response;
} catch (e) {
err = e;
retryTimes += 1;
}
}
throw err;
};
}
+266
View File
@@ -0,0 +1,266 @@
import VirtualDirectory, { VirtualFile } from '@/class/VirtualDirectory'
import {
getOption,
getResponse,
miaoFetchConfig,
deleteOption,
uploadOption,
queryOption,
renameOption,
cutOption,
mkdirOption
} from '@/types/fetch'
import Config from '@/config'
import axios, { AxiosRequestConfig } from 'axios'
export const useMiaoFetch = (option?: miaoFetchConfig) => {
const retry = option?.retry ?? 0
const controller = new AbortController()
let flag = true
return {
miaoFetch: async (config: AxiosRequestConfig<any>) => {
let counter = 0
let response: any
let errList = []
while (flag && counter <= retry) {
try {
response = await axios({
...config,
signal: controller.signal
})
return response
} catch (_e) {
errList.push(_e)
counter += 1
}
}
throw errList
},
/**
* 强制终止miaoFetch
*/
abortMiaoFetch: () => {
flag = false
controller.abort()
}
}
}
const miaoFetchApi = {
/**
* 获取对应文件夹下的数据
*/
async get(
vDirectory: VirtualDirectory,
option?: getOption
): Promise<getResponse> {
const { baseUrl, api } = Config
const url = `${baseUrl}${api.get}${vDirectory.path}`
const retry = option?.retry ?? 0
const { miaoFetch } = useMiaoFetch({
retry
})
const response = await miaoFetch({
url
})
return response.data
},
/**
* 上传单个文件到对应文件夹, 后续要将data类型改成buffer以支持分片上传
* 正常上传文件请使用uploadQueue
*/
upload(data: File, targetVDir: VirtualDirectory, option?: uploadOption) {
const { baseUrl, api } = Config
const url = `${baseUrl}${api.upload}${targetVDir.path}`
const retry = option?.retry ?? 0
const { miaoFetch, abortMiaoFetch } = useMiaoFetch({
retry
})
const sizeTotal = data.size
const opType = option?.type ?? 'write'
const formData = new FormData()
formData.append('file', data)
// 必须这样传,不然中文乱码
formData.append('fileName', data.name)
formData.append('operateType', opType)
return {
abort: () => abortMiaoFetch(),
response: new Promise<{
message: 'success' | 'failed'
error?: string
}>(async (resolve) => {
const response = await miaoFetch({
url,
method: 'post',
data: formData,
onUploadProgress(progressEvent) {
option &&
option.onProcess &&
option.onProcess(progressEvent.loaded / sizeTotal)
}
})
resolve(response.data)
})
}
},
/**
* 在目标文件夹下创建新的文件夹
*/
mkdir(
targetVDir: VirtualDirectory,
newFolderName: string,
option?: mkdirOption
) {
const { baseUrl, api } = Config
const url = `${baseUrl}${api.mkdir}${targetVDir.path}`
const { miaoFetch } = useMiaoFetch({
retry: option?.retry ?? 0
})
return new Promise<{
message: 'success' | 'failed'
error?: string
}>(async (resolve) => {
const response = await miaoFetch({
url,
method: 'post',
data: {
folderName: newFolderName
}
})
resolve(response.data)
})
},
/**
* 在目标文件夹下创建新的空文件,实际上是通过upload空文件实现
*/
mkFile(
targetVDir: VirtualDirectory,
newFileName: string,
option?: uploadOption
) {
const emptyBlob = new Blob([])
const emptyFile = new File([emptyBlob], newFileName, {
type: 'text/plain'
})
return this.upload(emptyFile, targetVDir, option)
},
/**
* 删除对应的文件或文件夹,若为文件夹会递归删除
*/
delete(target: VirtualFile | VirtualDirectory, option?: deleteOption) {
const { baseUrl, api } = Config
const url = `${baseUrl}${api.delete}${target.path}`
const retry = option?.retry ?? 0
const { miaoFetch } = useMiaoFetch({
retry
})
return {
response: new Promise<{
eventId: number
}>(async (resolve) => {
const response = await miaoFetch({
url,
method: 'post'
})
resolve(response.data)
})
}
},
/**
* 重命名对应的文件或文件夹
*/
rename(
target: VirtualFile | VirtualDirectory,
newName: string,
option?: renameOption
) {
const { baseUrl, api } = Config
const url = `${baseUrl}${api.rename}${target.path}`
const retry = option?.retry ?? 0
const { miaoFetch } = useMiaoFetch({
retry
})
return {
response: new Promise<{
eventId: number
}>(async (resolve) => {
const response = await miaoFetch({
url,
method: 'post',
data: { newName }
})
resolve(response.data)
})
}
},
/**
* 剪切文件或文件夹
*/
cut(
target: VirtualFile | VirtualDirectory,
to: VirtualDirectory,
option?: cutOption
) {
const newPath = to.path
const { baseUrl, api } = Config
const url = `${baseUrl}${api.cut}${target.path}`
const retry = option?.retry ?? 0
const { miaoFetch } = useMiaoFetch({
retry
})
return {
response: new Promise<{
eventId: number
}>(async (resolve) => {
const response = await miaoFetch({
url,
method: 'post',
data: { newPath }
})
resolve(response.data)
})
}
},
/**
* 查询服务端操作事件的进展
*/
query(eventId: number, option?: queryOption) {
const { baseUrl, api } = Config
const url = `${baseUrl}${api.query}`
const retry = option?.retry ?? 0
const { miaoFetch } = useMiaoFetch({
retry
})
return {
response: new Promise<{
status: 'process' | 'success' | 'failed'
error?: unknown
}>(async (resolve) => {
const response = await miaoFetch({
url,
method: 'get',
params: {
id: eventId
}
})
resolve(response.data)
})
}
}
}
export default function useMiaoFetchApi() {
return miaoFetchApi
}
+11
View File
@@ -0,0 +1,11 @@
import UploadQueue from "@/class/UploadQueue";
import { reactive } from "vue";
let uploadQueue: UploadQueue
export default () => {
if(uploadQueue === undefined){
uploadQueue = reactive(new UploadQueue())
}
return uploadQueue
}
+11
View File
@@ -0,0 +1,11 @@
import VirtualPage from "@/class/VirtualPage"
import { Reactive, reactive } from "vue"
let views: Reactive<VirtualPage[]>
export default function useViretualPages(){
if(views === undefined) {
views = reactive<VirtualPage[]>([])
}
return views
}
+29
View File
@@ -0,0 +1,29 @@
import { directory, file } from "./type";
export type miaoFetchConfig = {
retry?: number;
};
export type getOption = {} & miaoFetchConfig;
export type getResponse = (file | directory)[];
export type uploadOption = {
/**
* 上传进度回调函数
* @param {any} percent 进度百分比,float类型
*/
onProcess?: (percent: number) => void;
/**
* 上传文件执行的操作
* write即为覆盖写
* append即为增量写
*/
type?: "write" | "append";
} & miaoFetchConfig;
export type deleteOption = {} & miaoFetchConfig;
export type renameOption = {} & miaoFetchConfig;
export type cutOption = {} & miaoFetchConfig
export type mkdirOption = {} & miaoFetchConfig
export type queryOption = {} & miaoFetchConfig;
+433 -90
View File
@@ -1,17 +1,23 @@
<template> <template>
<miao-drop-handler @on-virtual-directory="handleDropVDirectory" @on-files="handleDropFiles"
@on-virtual-files="handleDropVirtualFiles">
<div class="miao-directory-item-container" ref="rootDomRef"> <div class="miao-directory-item-container" ref="rootDomRef">
<div class="container-top"> <div class="container-top" :style="{
<div class="container-top-colorbar" :style="{ backgroundColor: props.color }"></div> backgroundColor:
index % 2 === 0 ? '#f8f8f8' : 'rgb(240 240 240)'
}">
<div class="container-top-colorfulBar" :style="{ backgroundColor: props.color }"></div>
<div class="container-top-breadcrumb"> <div class="container-top-breadcrumb">
<!-- <n-scrollbar x-scrollable> --> <!-- <n-scrollbar x-scrollable> -->
<div class="container-top-breadcrumb-container"> <div class="container-top-breadcrumb-container">
<n-breadcrumb separator=">" style="margin-left: 5px;"> <n-breadcrumb separator=">" style="margin-left: 5px">
<n-breadcrumb-item :clickable="false"> <n-breadcrumb-item :clickable="false">
<n-icon size="18"> <n-icon size="18">
<CloudOutline /> <CloudOutline />
</n-icon> </n-icon>
</n-breadcrumb-item> </n-breadcrumb-item>
<n-breadcrumb-item v-for="(dir) in currentDirectory?.directoryArray" @click="setCurrentDirectory(dir)" :clickable="true"> <n-breadcrumb-item v-for="dir in currentDirectory?.getParents"
@click="setCurrentDirectory(dir)" :clickable="true">
<div>{{ dir.name }}</div> <div>{{ dir.name }}</div>
</n-breadcrumb-item> </n-breadcrumb-item>
</n-breadcrumb> </n-breadcrumb>
@@ -30,128 +36,408 @@
</n-icon> </n-icon>
</div> </div>
</div> </div>
<div class="container-items" :style="{ backgroundColor: props.index % 2 === 0 ? '#f8f8f8' : 'rgb(240 240 240)' }"> <div class="container-items" :style="{
backgroundColor:
index % 2 === 0 ? '#f8f8f8' : 'rgb(240 240 240)'
}">
<n-scrollbar> <n-scrollbar>
<miaoDirectoryItem v-for="(dir) in currentDirectory?.directorys" @click="setCurrentDirectory(dir)" :item="dir" :key="dir.uid" :color="props.color" /> <transition-group name="dirItem">
<miaoDirectoryItem <miaoDirectoryItem v-for="dir in showData_directory" :item="dir" :key="dir.uid"
v-for="(file) in currentDirectory?.files" :color="props.color" :selected="selectedItem.value.includes(dir)"
:item="file" @delete="handleItemDelete(dir)" @click="handleItemClick(dir)"
:key="file.uid" @drag-start="handleItemDragStart" @rename="handleItemRename(dir)"
@click="openUrl(`${baseUrl}${api.get}${file.path}`)" @on-selected="handleItemSelect(dir)" />
@download="openUrl(`${baseUrl}${api.get}${file.path}`, {download: file.name})" </transition-group>
:color="props.color" <transition-group name="dirItem">
/> <miaoDirectoryItem v-for="file in showData_files" :item="file" :key="file.uid"
:color="props.color" :selected="selectedItem.value.includes(file)"
@click="handleItemClick(file)" @download="handleItemDownload(file)"
@delete="handleItemDelete(file)" @drag-start="handleItemDragStart"
@rename="handleItemRename(file)" @on-selected="handleItemSelect(file)" />
</transition-group>
</n-scrollbar> </n-scrollbar>
</div> </div>
<div class="container-bottom" :style="{ backgroundColor: props.index % 2 === 1 ? 'rgb(61 61 61)' : 'rgb(162 162 162)' }"></div> <div class="container-bottom" :style="{
<miaoMask v-model:show="showModel"></miaoMask> backgroundColor:
index % 2 === 1 ? 'rgb(61 61 61)' : 'rgb(162 162 162)'
}">
<div class="container-bottom-item">
<div class="container-bottom-item-icon">
<add-outline :style="{
color:
index % 2 === 0
? 'rgb(0 0 0)'
: 'rgb(255 255 255)'
}" @click="handleAddNewItem" />
</div> </div>
</div>
<div class="container-bottom-item">
<div class="container-bottom-item-icon">
<cloud-upload-outline :style="{
color:
index % 2 === 0
? 'rgb(0 0 0)'
: 'rgb(255 255 255)'
}" @click="handlePickFilesUpload" />
</div>
</div>
</div>
<miao-mask v-model:show="showModel"></miao-mask>
<miao-popup-input ref="popupInput"></miao-popup-input>
</div>
</miao-drop-handler>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { NBreadcrumbItem, NBreadcrumb, NIcon, NScrollbar } from 'naive-ui' import { NBreadcrumbItem, NBreadcrumb, NIcon, NScrollbar } from 'naive-ui'
import type { file, directory } from '@/types/type.ts' import VirtualDirectory, { VirtualFile } from '@/class/VirtualDirectory'
import VirtualDirectory from '@/class/virtualDirectory'; import { computed, onMounted, reactive, ref } from 'vue'
import { onMounted, ref } from 'vue';
import Config from '@/config' import Config from '@/config'
import dropHandler, { dropHandlerHooks } from '@/hooks/dropHandler'; import miaoMask from '@/components/miaoMask.vue'
import miaoMask from '@/components/miaoMask.vue'; import miaoDirectoryItem from '@/components/miaoDirectory/miaoDirectoryItem.vue'
import miaoDirectoryItem from '@/components/miaoDirectory/miaoDirectoryItem.vue'; import miaoPopupInput from '@/components/miaoPopupInput.vue'
import useMiaoFetch from '@/hooks/useMiaoFetch'; import miaoDropHandler from '@/components/miaoDropHandler.vue'
import useDataBus from '@/hooks/useDataBus'; import useMiaoFetchApi from '@/hooks/useMiaoFetchApi'
import { CloudOutline, ChevronBackOutline, ReloadOutline, CloseOutline } from '@vicons/ionicons5' import useDataBus from '@/hooks/useDataBus'
import {
CloudOutline,
ChevronBackOutline,
ReloadOutline,
CloseOutline,
CloudUploadOutline,
AddOutline
} from '@vicons/ionicons5'
import useUploadQueue from '@/hooks/useUploadQueue'
import useVirtualPages from '@/hooks/useVirtualPages'
import { filePicker } from '@/hooks/miaoTools'
import { uniq } from 'lodash'
const { baseUrl, api } = Config const { baseUrl, api } = Config
const dataBus = useDataBus() const dataBus = useDataBus()
const views = useVirtualPages()
const miaoFetch = useMiaoFetch({ const miaoFetchApi = useMiaoFetchApi()
retry: 5,
})
const props = defineProps<{ const props = defineProps<{
color: string color: string
index: number id: number
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
exit: [] exit: []
}>() }>()
// 目前展示的Dir const popupInput = ref()
const currentDirectory = defineModel<VirtualDirectory | undefined>('currentDirectory', { required: true })
// 是否显示模态框 // 是否显示模态框
const showModel = ref(0) const showModel = ref(0)
class SelectedItem {
constructor() {
this._selectedItem = []
}
_selectedItem: (VirtualDirectory | VirtualFile)[]
push(item: VirtualDirectory | VirtualFile) {
this._selectedItem = [item, ...this._selectedItem]
}
remove(item: VirtualDirectory | VirtualFile) {
this._selectedItem = this._selectedItem.filter(v => v !== item)
}
clear() {
this._selectedItem = []
}
// 保证内容仍然存在于dir中且各个元素不重复
get value() {
return uniq(this._selectedItem).filter(v => {
if (currentDirectory.value === undefined) {
return false
}
// @ts-ignore
return [...currentDirectory.value?.directorys, ...currentDirectory.value?.files].includes(v)
})
}
}
// 已选择的item,用于多选功能
const selectedItem = reactive(new SelectedItem())
const currentObjects = defineModel<VirtualDirectory[]>('currentObjects', {
required: true
})
// 目前展示的Dir
const currentDirectory = computed(() => {
return currentObjects.value[0]
})
// 当前组件在views中的序号
const index = computed(() => {
for (let i in views) {
if (views[i].uid === props.id) {
return parseInt(i)
}
}
return 0
})
// 用于展示的数据,后续会增加排序等操作
const showData_directory = computed<VirtualDirectory[]>(() => {
const data = currentDirectory.value?.directorys
? [...currentDirectory.value?.directorys]
: []
return data
})
const showData_files = computed<VirtualFile[]>(() => {
const data = currentDirectory.value?.files
? [...currentDirectory.value?.files]
: []
return data
})
// 用于监听拖拽文件事件 // 用于监听拖拽文件事件
const rootDomRef = ref<HTMLDivElement>() const rootDomRef = ref<HTMLDivElement>()
const uploadQueue = useUploadQueue()
// 设置显示的dir // 设置显示的dir
const setCurrentDirectory = async (virtualDirectory: VirtualDirectory) => { const setCurrentDirectory = async (virtualDirectory: VirtualDirectory) => {
// 若没有缓存数据则同步刷新,有缓存数据则异步刷新 // 若没有缓存数据则同步刷新,有缓存数据则异步刷新
if (virtualDirectory.files === undefined || virtualDirectory.directorys === undefined) { if (
const data: (file | directory)[] = await (await miaoFetch(`${baseUrl}${api.get}${virtualDirectory.path}`)).json() virtualDirectory.files === undefined ||
virtualDirectory.updateContent(data) virtualDirectory.directorys === undefined
) {
await virtualDirectory.update()
} else { } else {
; (async () => { virtualDirectory.update()
const data: (file | directory)[] = await (await miaoFetch(`${baseUrl}${api.get}${virtualDirectory.path}`)).json()
virtualDirectory.updateContent(data)
currentDirectory.value = undefined
currentDirectory.value = virtualDirectory
})()
} }
// 刷新一下 currentObjects.value[0] = virtualDirectory
currentDirectory.value = undefined
currentDirectory.value = virtualDirectory
// emit("onCurrentDirectoryChange", currentDirectory.value)
} }
const openUrl = (href: string, config?: { const reload = () => {
setCurrentDirectory(currentDirectory.value)
}
const openUrl = (
href: string,
config?: {
download?: string download?: string
target?: string target?: string
}) => { }
let {target, download} = config ?? {} ) => {
let { target, download } = config ?? {}
console.log({target, download}) const a = document.createElement('a')
const a = document.createElement('a'); a.setAttribute('href', href)
a.setAttribute('href', href);
a.setAttribute('target', target ?? '_blank') a.setAttribute('target', target ?? '_blank')
a.setAttribute('download', download ?? ''); download && a.setAttribute('download', download)
a.click(); a.click()
// var a = document.createElement("a");
// a.setAttribute('href', href)
// a.setAttribute('target', target ?? '_blank')
// a.setAttribute('download', download ?? '')
// console.log({target, download})
// a.click();
} }
const handleBack = () => { const handleBack = () => {
if(currentDirectory.value?.parent){ if (currentDirectory.value?.parent) {
setCurrentDirectory(currentDirectory.value.parent) setCurrentDirectory(currentDirectory.value.parent)
} }
} }
const handleReload = () => { const handleReload = () => {
currentDirectory.value && setCurrentDirectory(currentDirectory.value) reload()
} }
onMounted(async () => { const handleItemClick = (item: VirtualDirectory | VirtualFile) => {
currentDirectory.value && await setCurrentDirectory(currentDirectory.value) if (selectedItem.value.length > 0) {
// 拖动事件处理 handleItemSelect(item)
const dropFileOption:dropHandlerHooks = { } else {
onDropFiles(files: File[]) { if (item.type === 'file') {
const dragData = dataBus.get('dragData') openUrl(`${baseUrl}${api.get}${item.path}`)
console.log({dragData, files}) } else if (item.type === 'directory') {
}, setCurrentDirectory(item)
onEnter() {
showModel.value += 1
},
onEnd() {
showModel.value -= 1
},
} }
rootDomRef.value && dropHandler(rootDomRef.value, dropFileOption) }
}
const handleItemDownload = (item: VirtualFile) => {
openUrl(`${baseUrl}${api.get}${item.path}`, {
download: item.name
})
}
const handleItemDelete = async (_item: VirtualDirectory | VirtualFile) => {
for (let item of uniq([...selectedItem.value, _item])) {
; (async () => {
const { response } = miaoFetchApi.delete(item, {
retry: 5
})
// todo: 将删除事件统一用一个事件管理中心管理
const id = (await response).eventId
const { response: res } = miaoFetchApi.query(id)
const eventResult = await res
if (eventResult.status === 'success') {
reload()
}
})()
}
}
const handleItemRename = async (item: VirtualDirectory | VirtualFile) => {
const popupRes = await popupInput.value.popup({
title: '重命名',
showInput: true,
inputValue: item.name,
inputProps: {
placeholder: item.name
},
options: [
{
label: '取消',
key: false,
type: 'error'
},
{
label: '确认',
key: true,
type: 'success'
}
]
})
if (popupRes.key === false) {
return
}
const newName = popupRes.text
const { response } = miaoFetchApi.rename(item, newName, {
retry: 5
})
const id = (await response).eventId
const { response: res } = miaoFetchApi.query(id)
const eventResult = await res
if (eventResult.status === 'success') {
reload()
}
}
const handleItemDragStart = async (
_event: DragEvent,
item: VirtualDirectory | VirtualFile
) => {
const items = uniq([item, ...selectedItem.value])
dataBus.set('dragData_vFiles', items.filter(v => v.type === 'file'))
dataBus.set('dragData_vDirectory', items.filter(v => v.type === 'directory'))
selectedItem.clear()
}
const handleDropFiles = async (files: File[]) => {
currentDirectory.value &&
uploadQueue.push(files, currentDirectory.value, {
onFinish() {
reload()
}
})
}
const handleDropVDirectory = async (vDirs: VirtualDirectory[]) => {
// 不能移到自己或自己的子文件夹内
for (let vDir of vDirs) {
if (currentDirectory.value.getParents.includes(vDir)) {
return
}
}
for (let dir of vDirs) {
; (async () => {
const _from = dir.parent
const { response } = miaoFetchApi.cut(dir, currentDirectory.value)
const id = (await response).eventId
const { response: res } = miaoFetchApi.query(id)
const eventResult = await res
if (eventResult.status === 'success') {
reload()
_from && _from.update()
}
})()
}
}
const handleDropVirtualFiles = (files: VirtualFile[]) => {
if (files[0].parent === currentDirectory.value) {
return
}
for (let file of files) {
; (async () => {
const _from = file.parent
const { response } = miaoFetchApi.cut(file, currentDirectory.value)
const id = (await response).eventId
const { response: res } = miaoFetchApi.query(id)
const eventResult = await res
if (eventResult.status === 'success') {
reload()
_from.update()
}
})()
}
}
const handlePickFilesUpload = async () => {
const files = await filePicker({
multiple: true
})
const _currDir = currentDirectory.value
uploadQueue.push(files, _currDir, {
onFinish() {
_currDir.update()
}
})
}
const handleAddNewItem = async () => {
const popupRes = await popupInput.value.popup({
title: '新建文件/文件夹',
showInput: true,
inputProps: {
placeholder: ''
},
options: [
{
label: '取消',
key: 'cancel',
type: 'error'
},
{
label: '文件',
key: 'file',
type: 'success'
},
{
label: '文件夹',
key: 'dir',
type: 'success'
}
]
})
// todo: 上传前如重名文件夹等等的错误提前检查
if (popupRes.key === 'cancel' || popupRes.text === '') {
return
}
const _currDir = currentDirectory.value
const name = popupRes.text
const opType: 'file' | 'dir' = popupRes.key
if (opType === 'dir') {
const res = await miaoFetchApi.mkdir(currentDirectory.value, name)
if (res.message === 'success') {
_currDir.update()
}
} else {
const { response } = miaoFetchApi.mkFile(currentDirectory.value, name)
const res = await response
if (res.message === 'success') {
_currDir.update()
}
}
}
const handleItemSelect = (item: VirtualDirectory | VirtualFile) => {
if (!selectedItem.value.includes(item)) {
selectedItem.push(item)
} else {
selectedItem.remove(item)
}
}
onMounted(async () => {
await setCurrentDirectory(currentDirectory.value)
}) })
</script> </script>
@@ -163,10 +449,11 @@ $bottom-bar-height: 60px;
position: relative; position: relative;
height: 100%; height: 100%;
width: inherit; width: inherit;
min-width: 266px; // min-width: 236px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
overflow: hidden; overflow: hidden;
.container-top { .container-top {
height: $top-height; height: $top-height;
width: 100%; width: 100%;
@@ -176,12 +463,14 @@ $bottom-bar-height: 60px;
align-items: center; align-items: center;
overflow: hidden; overflow: hidden;
background-color: #f1f1f1; background-color: #f1f1f1;
.container-top-colorbar {
.container-top-colorfulBar {
height: 70%; height: 70%;
width: 5px; width: 5px;
margin-left: 10px; margin-left: 10px;
border-radius: 3px 0 0 3px; border-radius: 3px 0 0 3px;
} }
.container-top-breadcrumb { .container-top-breadcrumb {
position: relative; position: relative;
height: 70%; height: 70%;
@@ -195,6 +484,7 @@ $bottom-bar-height: 60px;
background-color: #ffffff; background-color: #ffffff;
padding: 0 5px; padding: 0 5px;
border-radius: 0 3px 3px 0; border-radius: 0 3px 3px 0;
.container-top-breadcrumb-container { .container-top-breadcrumb-container {
position: absolute; position: absolute;
height: 100%; height: 100%;
@@ -206,6 +496,7 @@ $bottom-bar-height: 60px;
align-items: center; align-items: center;
} }
} }
.container-top-tools { .container-top-tools {
position: relative; position: relative;
height: 100%; height: 100%;
@@ -214,6 +505,7 @@ $bottom-bar-height: 60px;
display: flex; display: flex;
justify-content: space-around; justify-content: space-around;
align-items: center; align-items: center;
.container-top-tools-item { .container-top-tools-item {
width: 20px; width: 20px;
height: 20px; height: 20px;
@@ -224,39 +516,90 @@ $bottom-bar-height: 60px;
border-radius: 5px; border-radius: 5px;
transition: background-color 0.3s; transition: background-color 0.3s;
cursor: pointer; cursor: pointer;
.container-top-tools-item-reload { .container-top-tools-item-reload {
transition: transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out;
} }
&:hover { &:hover {
background-color: rgba(128,128,128,0.4); background-color: rgba(128, 128, 128, 0.4);
} }
&:active .container-top-tools-item-reload { &:active .container-top-tools-item-reload {
transform: rotate(360deg); transform: rotate(360deg);
} }
} }
&::after {
content: ''; // &::after {
height: 60%; // content: '';
position: absolute; // height: 60%;
right: -1px; // position: absolute;
width: 2px; // right: -2px;
background-color: #828282; // width: 2px;
} // background-color: #828282;
// }
} }
} }
.container-items { .container-items {
width: 100%; width: 100%;
height: calc(100% - $top-height - $bottom-bar-height); height: calc(100% - $top-height - $bottom-bar-height);
// flex: 1;
} }
.container-bottom { .container-bottom {
height: $bottom-bar-height; height: $bottom-bar-height;
background-color: bisque; background-color: bisque;
display: flex; display: flex;
justify-content: center; justify-content: space-around;
align-items: center; align-items: center;
user-select: none; user-select: none;
box-shadow: 0px 1px 10px #888888; box-shadow: 0px 1px 10px #888888;
z-index: 2; z-index: 2;
.container-bottom-item {
height: 40px;
width: 40px;
display: flex;
justify-content: center;
align-items: center;
.container-bottom-item-icon {
svg {
width: 30px;
height: 30px;
transition: all 0.3s ease;
cursor: pointer;
}
&:hover {
svg {
width: 40px;
height: 40px;
}
}
}
}
} }
} }
</style>
// transition动画相关
// .miao-directory-item-container {
// .container-items {
// .dirItem-move {
// transition: all 0.2s ease;
// }
// .dirItem-leave-active {
// transition: none;
// }
// .dirItem-enter-from {
// opacity: 0;
// }
// .dirItem-leave-active {
// position: absolute;
// }
// }
// }</style>
+46 -13
View File
@@ -1,37 +1,70 @@
import { defineConfig } from "vite"; import { defineConfig } from 'vite'
import vue from "@vitejs/plugin-vue"; import vue from '@vitejs/plugin-vue'
import { resolve } from "path"; import { resolve } from 'path'
import { viteSingleFile } from 'vite-plugin-singlefile'
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [vue()], plugins: [vue(), viteSingleFile()],
resolve: { resolve: {
alias: { alias: {
"@": resolve(__dirname, "src") '@': resolve(__dirname, 'src')
} }
}, },
server: { server: {
proxy: { proxy: {
"/get": { '/get': {
target: "http://127.0.0.1:17705", target: 'http://127.0.0.1:17705',
changeOrigin: true, changeOrigin: true,
rewrite: path => path.replace(/^\/get/, "/get") rewrite: (path) => path.replace(/^\/get/, '/get')
},
'/upload': {
target: 'http://127.0.0.1:17705',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/upload/, '/upload')
},
'/delete': {
target: 'http://127.0.0.1:17705',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/delete/, '/delete')
},
'/query': {
target: 'http://127.0.0.1:17705',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/query/, '/query')
},
'/rename': {
target: 'http://127.0.0.1:17705',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/rename/, '/rename')
},
'/cut': {
target: 'http://127.0.0.1:17705',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/cut/, '/cut')
},
'/mkdir': {
target: 'http://127.0.0.1:17705',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/mkdir/, '/mkdir')
} }
} }
}, },
build: { build: {
rollupOptions: { rollupOptions: {
input: { input: {
main: resolve(__dirname, "index.html") main: resolve(__dirname, 'index.html')
}, },
output: { output: {
// 配置输出为单文件 // 配置输出为单文件
inlineDynamicImports: true, inlineDynamicImports: true,
manualChunks: undefined, manualChunks: undefined,
entryFileNames: "bundle.js", entryFileNames: 'bundle.js',
format: "iife", // 立即执行函数格式 format: 'iife', // 立即执行函数格式
name: "MyBundle" name: 'MyBundle'
} }
} }
} }
}); })