feat: 添加prettier格式化代码

This commit is contained in:
539943419 committed 2024-12-25 19:44:18 +08:00
1 parent 5823d5876b
commit f33e9386cd
81 files changed
+8084 -7365

No files matched your search

+104
View File
@@ -0,0 +1,104 @@
export default {
/**
* 换行宽度,当代码宽度达到多少时换行
* @default 80
* @type {number}
*/
printWidth: 80,
/**
* 缩进的空格数量
* @default 2
* @type {number}
*/
tabWidth: 3,
/**
* 是否使用制表符代替空格
* @default false
* @type {boolean}
*/
useTabs: false,
/**
* 是否在代码块结尾加上分号
* @default true
* @type {boolean}
*/
semi: false,
/**
* 是否使用单引号替代双引号
* @default false
* @type {boolean}
*/
singleQuote: true,
/**
* 对象属性的引号处理
* @default "as-needed"
* @type {"as-needed"|"consistent"|"preserve"}
*/
quoteProps: 'as-needed',
/**
* jsx中是否使用单引号替代双引号
* @default false
* @type {boolean}
*/
jsxSingleQuote: true,
/**
* 在jsx中使用是否单引号代替双引号
* @default false
* @type {boolean}
*/
/**
* 末尾是否加上逗号
* @default "es5"
* @type {"es5"|"none"|"all"}
*/
trailingComma: 'none',
/**
* 在对象,数组括号与文字之间加空格 "{ foo: bar }"
* @default true
* @type {boolean}
*/
bracketSpacing: true,
/**
* 把多行HTML (HTML, JSX, Vue, Angular)元素的>放在最后一行的末尾,而不是单独放在下一行(不适用于自关闭元素)。
* @default false
* @type {boolean}
*/
bracketSameLine: false,
/**
* 当箭头函数只有一个参数是否加括号
* @default "always"
* @type {"always"|"avoid"}
*/
arrowParens: 'always',
/**
* 为HTML、Vue、Angular和Handlebars指定全局空格敏感性
* @default "css"
* @type {"css"|"strict"|"ignore"}
*/
htmlWhitespaceSensitivity: 'ignore',
/**
* 是否缩进Vue文件中的<script>和<style>标记内的代码。有些人(比如Vue的创建者)不使用缩进来保存缩进级别,但这可能会破坏编辑器中的代码折叠。
* @default "always"
* @type {"always"|"avoid"}
*/
vueIndentScriptAndStyle: false,
/**
* 文件结束符
* @default "lf"
* @type {"lf"|"crlf"|"cr"|"auto"}
*/
endOfLine: 'crlf',
/**
* 因为使用了一些折行敏感型的渲染器(如GitHub comment)而按照markdown文本样式进行折行
*/
proseWrap: 'never',
// 是否使用根目录下的EditorConfig配置文件
useEditorConfig: false,
/**
* HTML\VUE\JSX每行只有单个属性
* @default true
* @type {boolean}
*/
singleAttributePerLine: true,
disableLanguages: ['html']
}
+4 -1
View File
@@ -9,7 +9,8 @@
"build": "vue-tsc -b && vite build", "build": "vue-tsc -b && vite build",
"build:auto": "pnpm run build && go env -w GOOS=windows GOARCH=amd64 && rm -rf ./src-server/web/* && cp -r ./dist/* ./src-server/web/ && cd ./src-server && go env -w GOOS=windows && go build -o ../miao-directory.exe", "build:auto": "pnpm run build && go env -w GOOS=windows GOARCH=amd64 && rm -rf ./src-server/web/* && cp -r ./dist/* ./src-server/web/ && cd ./src-server && go env -w GOOS=windows && go build -o ../miao-directory.exe",
"build:auto:release": "pnpm run build && rm -rf ./src-server/web/* && cp -r ./dist/* ./src-server/web/ && cd ./src-server && go env -w GOOS=windows GOARCH=amd64 && go build -o ../miao-directory-amd64-win.exe && go env -w GOOS=linux GOARCH=amd64 && go build -o ../miao-directory-amd64-linux", "build:auto:release": "pnpm run build && rm -rf ./src-server/web/* && cp -r ./dist/* ./src-server/web/ && cd ./src-server && go env -w GOOS=windows GOARCH=amd64 && go build -o ../miao-directory-amd64-win.exe && go env -w GOOS=linux GOARCH=amd64 && go build -o ../miao-directory-amd64-linux",
"preview": "vite preview" "preview": "vite preview",
"format": "prettier --write src/"
}, },
"dependencies": { "dependencies": {
"@codemirror/lang-go": "^6.0.1", "@codemirror/lang-go": "^6.0.1",
@@ -51,6 +52,8 @@
"@types/node": "^22.1.0", "@types/node": "^22.1.0",
"@types/pdfjs-dist": "^2.10.378", "@types/pdfjs-dist": "^2.10.378",
"@vitejs/plugin-vue": "^5.1.2", "@vitejs/plugin-vue": "^5.1.2",
"prettier": "^3.4.2",
"prettier-plugin-vue": "^1.1.6",
"rollup-plugin-visualizer": "^5.12.0", "rollup-plugin-visualizer": "^5.12.0",
"typescript": "^5.5.3", "typescript": "^5.5.3",
"vite": "^5.4.0", "vite": "^5.4.0",
+27
View File
@@ -120,6 +120,12 @@ importers:
'@vitejs/plugin-vue': '@vitejs/plugin-vue':
specifier: ^5.1.2 specifier: ^5.1.2
version: 5.1.2(vite@5.4.0(@types/node@22.1.0)(sass@1.77.8))(vue@3.5.0(typescript@5.5.4)) version: 5.1.2(vite@5.4.0(@types/node@22.1.0)(sass@1.77.8))(vue@3.5.0(typescript@5.5.4))
prettier:
specifier: ^3.4.2
version: 3.4.2
prettier-plugin-vue:
specifier: ^1.1.6
version: 1.1.6
rollup-plugin-visualizer: rollup-plugin-visualizer:
specifier: ^5.12.0 specifier: ^5.12.0
version: 5.12.0(rollup@4.20.0) version: 5.12.0(rollup@4.20.0)
@@ -1101,6 +1107,19 @@ packages:
resolution: {integrity: sha512-Aweb9unOEpQ3ezu4Q00DPvvM2ZTUitJdNKeP/+uQgr1IBIqu574IaZoURId7BKtWMREwzKa9OgzPzezWGPWFQw==} resolution: {integrity: sha512-Aweb9unOEpQ3ezu4Q00DPvvM2ZTUitJdNKeP/+uQgr1IBIqu574IaZoURId7BKtWMREwzKa9OgzPzezWGPWFQw==}
engines: {node: ^10 || ^12 || >=14} engines: {node: ^10 || ^12 || >=14}
prettier-plugin-vue@1.1.6:
resolution: {integrity: sha512-trQ/oY+6hSsGe2zPIFThXMIM0TbxMEbk2VOrKjwHWuSz7OEo0rnumbz9a47OxVPCaAnGY9vZG8qDTiTmk9bq0A==}
prettier@2.8.8:
resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==}
engines: {node: '>=10.13.0'}
hasBin: true
prettier@3.4.2:
resolution: {integrity: sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==}
engines: {node: '>=14'}
hasBin: true
promise-polyfill@7.1.0: promise-polyfill@7.1.0:
resolution: {integrity: sha512-P6NJ2wU/8fac44ENORsuqT8TiolKGB2u0fEClPtXezn7w5cmLIjM/7mhPlTebke2EPr6tmqZbXvnX0TxwykGrg==} resolution: {integrity: sha512-P6NJ2wU/8fac44ENORsuqT8TiolKGB2u0fEClPtXezn7w5cmLIjM/7mhPlTebke2EPr6tmqZbXvnX0TxwykGrg==}
@@ -2458,6 +2477,14 @@ snapshots:
picocolors: 1.0.1 picocolors: 1.0.1
source-map-js: 1.2.0 source-map-js: 1.2.0
prettier-plugin-vue@1.1.6:
dependencies:
prettier: 2.8.8
prettier@2.8.8: {}
prettier@3.4.2: {}
promise-polyfill@7.1.0: {} promise-polyfill@7.1.0: {}
proxy-from-env@1.1.0: {} proxy-from-env@1.1.0: {}
+378 -314
View File
@@ -1,14 +1,21 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, provide, ref, shallowRef, useTemplateRef } from 'vue' import {
computed,
onMounted,
provide,
ref,
shallowRef,
useTemplateRef
} from 'vue'
import { NIcon, NScrollbar, NDropdown } from 'naive-ui' import { NIcon, NScrollbar, NDropdown } from 'naive-ui'
import { import {
EyeOffOutline, EyeOffOutline,
EyeOutline, EyeOutline,
CloseOutline, CloseOutline,
CopyOutline, CopyOutline,
EllipsisVertical, EllipsisVertical,
QrCodeOutline, QrCodeOutline,
ExtensionPuzzleOutline ExtensionPuzzleOutline
} from '@vicons/ionicons5' } from '@vicons/ionicons5'
import type VirtualDirectory from './class/VirtualDirectory' import type VirtualDirectory from './class/VirtualDirectory'
import type { VirtualFile } from './class/VirtualDirectory' import type { VirtualFile } from './class/VirtualDirectory'
@@ -30,8 +37,8 @@ const showModal = ref<boolean>(false)
const viewRef = ref<HTMLDivElement>() const viewRef = ref<HTMLDivElement>()
const modalData = shallowRef<{ const modalData = shallowRef<{
component: any component: any
props: any props: any
}>() }>()
const messageProviderRef = useTemplateRef('messageProviderRef') const messageProviderRef = useTemplateRef('messageProviderRef')
@@ -43,79 +50,85 @@ const rootDirectory = useRootVDirectory()
// component就是一个vue组件,类似于miaoDirectory // component就是一个vue组件,类似于miaoDirectory
const createView = ( const createView = (
component: any, component: any,
name: string, name: string,
currentDirectories?: VirtualDirectory[], currentDirectories?: VirtualDirectory[],
currentFiles?: VirtualFile[], currentFiles?: VirtualFile[],
index?: number index?: number
) => { ) => {
views.push(component, name, currentDirectories, currentFiles, { index }) views.push(component, name, currentDirectories, currentFiles, { index })
} }
const deleteView = (index: number) => { const deleteView = (index: number) => {
views.deleteView(index) views.deleteView(index)
} }
// 点击标题是隐藏其他标签或显示其他标签,还挺好用的 // 点击标题是隐藏其他标签或显示其他标签,还挺好用的
const handleClickTitle = (index: number) => { const handleClickTitle = (index: number) => {
let count = views._views.filter((v) => v.visible).length let count = views._views.filter((v) => v.visible).length
let op = let op =
!views._views[index].visible || count > 1 ? 'hideOthers' : 'showOthers' !views._views[index].visible || count > 1 ? 'hideOthers' : 'showOthers'
let _index = 0 let _index = 0
while (_index < views._views.length) { while (_index < views._views.length) {
if (_index !== index) { if (_index !== index) {
views._views[_index].visible = op === 'hideOthers' ? false : true views._views[_index].visible = op === 'hideOthers' ? false : true
} else { } else {
views._views[_index].visible = true views._views[_index].visible = true
} }
_index += 1 _index += 1
} }
} }
const openMenuOption = computed(() => [ const openMenuOption = computed(
{ () =>
label: '分享', [
key: 'share', {
icon: renderIcon(QrCodeOutline) label: '分享',
}, pluginCenter.value ? { key: 'share',
label: '插件', icon: renderIcon(QrCodeOutline)
key: 'plugin', },
children: [ pluginCenter.value
...pluginCenter.value ? {
.getUsablePlugin([], [], { label: '插件',
group: [PluginGroup.mainMenu] key: 'plugin',
}) children: [
.map((v) => ({ ...pluginCenter.value
label: `${v.name}`, .getUsablePlugin([], [], {
key: `plugin:${v.key}`, group: [PluginGroup.mainMenu]
icon: v.icon ? renderIcon(v.icon) : undefined })
})) .map((v) => ({
], label: `${v.name}`,
icon: renderIcon(ExtensionPuzzleOutline) key: `plugin:${v.key}`,
} : undefined icon: v.icon ? renderIcon(v.icon) : undefined
].filter(v => v) as DropdownMixedOption[]) }))
],
icon: renderIcon(ExtensionPuzzleOutline)
}
: undefined
].filter((v) => v) as DropdownMixedOption[]
)
const handleMenuSelect = async (key: string) => { const handleMenuSelect = async (key: string) => {
if (key === 'share') { if (key === 'share') {
showModal.value = true showModal.value = true
modalData.value = { modalData.value = {
component: (await import('naive-ui/es/qr-code')).NQrCode, component: (await import('naive-ui/es/qr-code')).NQrCode,
props: { props: {
value: baseUrl, value: baseUrl,
size: 300, size: 300,
errorCorrectionLevel: 'H' errorCorrectionLevel: 'H'
} }
} }
} else if (key.startsWith('plugin:')) { } else if (key.startsWith('plugin:')) {
const pluginName = key.split(':')[1] const pluginName = key.split(':')[1]
pluginCenter.value && pluginCenter.value.usePlugin(pluginName, [], []) pluginCenter.value && pluginCenter.value.usePlugin(pluginName, [], [])
} }
} }
onMounted(async () => { onMounted(async () => {
// @ts-ignore // @ts-ignore
await init(messageProviderRef.value?.alertTip) await init(messageProviderRef.value?.alertTip)
pluginCenter.value = usePluginCenter() pluginCenter.value = usePluginCenter()
}) })
// @ts-ignore // @ts-ignore
@@ -124,72 +137,123 @@ provide('rootDirectory', rootDirectory)
</script> </script>
<template> <template>
<div class="view" ref="viewRef"> <div
<miao-message-provider ref="messageProviderRef"> class="view"
<div class="view-controller"> ref="viewRef"
<n-scrollbar x-scrollable> >
<div class="tabs-container"> <miao-message-provider ref="messageProviderRef">
<transition-group name="tab"> <div class="view-controller">
<div class="tab" v-for="(view, index) of views._views" :key="view.id"> <n-scrollbar x-scrollable>
<span class="tab-title" :title="view.title" @click="handleClickTitle(index)"> <div class="tabs-container">
{{ <transition-group name="tab">
view.title.length > 5 && 0 <div
? `${view.title.substring(0, 5)}...` class="tab"
: view.title v-for="(view, index) of views._views"
}} :key="view.id"
</span> >
<div class="tab-control"> <span
<div class="tab-point" :style="{ backgroundColor: view.color }"></div> class="tab-title"
<n-icon class="tag-control-icon icon" @click="view.switchShow()"> :title="view.title"
<EyeOutline v-show="view.visible" class="icon-inner" /> @click="handleClickTitle(index)"
<EyeOffOutline v-show="!view.visible" class="icon-inner" /> >
</n-icon> {{
<n-icon class="tag-control-icon icon" @click=" view.title.length > 5 && 0
createView( ? `${view.title.substring(0, 5)}...`
view.component, : view.title
view.name, }}
view.currentDirectories, </span>
view.currentFiles, <div class="tab-control">
index + 1 <div
) class="tab-point"
" v-if="view.allowCopy"> :style="{ backgroundColor: view.color }"
<CopyOutline /> ></div>
</n-icon> <n-icon
<n-icon class="tag-control-icon icon" @click="deleteView(index)"> class="tag-control-icon icon"
<CloseOutline class="icon-inner" /> @click="view.switchShow()"
</n-icon> >
</div> <EyeOutline
</div> v-show="view.visible"
</transition-group> class="icon-inner"
</div> />
</n-scrollbar> <EyeOffOutline
<div class="view-controller-menu"> v-show="!view.visible"
<div class="view-controller-menu-item"> class="icon-inner"
<n-dropdown trigger="click" :options="openMenuOption" @select="handleMenuSelect"> />
<n-icon class="icon"> </n-icon>
<EllipsisVertical class="icon-inner" /> <n-icon
</n-icon> class="tag-control-icon icon"
</n-dropdown> @click="
</div> createView(
</div> view.component,
view.name,
view.currentDirectories,
view.currentFiles,
index + 1
)
"
v-if="view.allowCopy"
>
<CopyOutline />
</n-icon>
<n-icon
class="tag-control-icon icon"
@click="deleteView(index)"
>
<CloseOutline class="icon-inner" />
</n-icon>
</div>
</div>
</transition-group>
</div>
</n-scrollbar>
<div class="view-controller-menu">
<div class="view-controller-menu-item">
<n-dropdown
trigger="click"
:options="openMenuOption"
@select="handleMenuSelect"
>
<n-icon class="icon">
<EllipsisVertical class="icon-inner" />
</n-icon>
</n-dropdown>
</div>
</div> </div>
<div class="view-container"> </div>
<!-- <transition-group name="page"> --> <div class="view-container">
<div class="view-container-item" v-for="(view, index) of views._views" <!-- <transition-group name="page"> -->
:class="!view.visible ? 'view-container-item-hidden' : ''" :key="view.id"> <div
<component :is="view.component" v-model:current-directories="view.currentDirectories" class="view-container-item"
v-model:current-files="view.currentFiles" :id="view.id" :color="view.color" :view="view" v-for="(view, index) of views._views"
:views="views" @exit="deleteView(index)"></component> :class="!view.visible ? 'view-container-item-hidden' : ''"
</div> :key="view.id"
<!-- </transition-group> --> >
<component
:is="view.component"
v-model:current-directories="view.currentDirectories"
v-model:current-files="view.currentFiles"
:id="view.id"
:color="view.color"
:view="view"
:views="views"
@exit="deleteView(index)"
></component>
</div> </div>
</miao-message-provider> <!-- </transition-group> -->
</div> </div>
<!-- 模态框展示,用来显示分享二维码,设置菜单之类的东西 --> </miao-message-provider>
<MiaoMask v-model:show="showModal" @click="showModal = false"> </div>
<component @click="(e: any) => e.stopPropagation()" :is="modalData?.component" v-bind="modalData?.props"> <!-- 模态框展示,用来显示分享二维码,设置菜单之类的东西 -->
</component> <MiaoMask
</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>
@@ -197,219 +261,219 @@ $controller-height: 25px;
$tag-width: 170px; $tag-width: 170px;
.view { .view {
background-color: #ffffff;
position: relative;
height: 100%;
width: 100%;
background-color: #ffffff; .view-controller {
position: relative; display: flex;
height: 100%; height: $controller-height;
width: 100%; width: 100%;
background-color: #dadada;
// overflow: hidden;
.view-controller { .tabs-container {
display: flex; display: flex;
height: $controller-height; margin-left: 5px;
width: 100%; flex: 1;
background-color: #dadada;
// overflow: hidden;
.tabs-container { // overflow-x: scroll;
display: flex; .tab {
margin-left: 5px;
flex: 1;
// overflow-x: scroll;
.tab {
position: relative;
width: $tag-width;
height: $controller-height;
margin: 0 5px;
// flex: 1;
display: flex;
border-radius: 5px 5px 0 0;
align-items: center;
.tab-title {
// font-family: monospace;
// font-weight: bolder;
margin-left: 4px;
width: 90px;
user-select: none;
cursor: pointer;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
span {
user-select: none;
cursor: pointer;
}
}
.tab-point {
height: 5px;
aspect-ratio: 1;
border-radius: 66px;
margin-right: 5px;
}
.tab-control {
position: absolute;
right: 10px;
display: flex;
align-items: center;
.tab-control-icon:not(:last-child) {
margin-right: 5px;
}
}
&:not(:last-child)::after {
content: '';
height: calc($controller-height * 0.6);
width: 1px;
border-right: 1px solid black;
position: absolute;
right: 0px;
}
}
}
.view-controller-menu {
position: relative; position: relative;
width: $tag-width;
height: $controller-height;
margin: 0 5px;
// flex: 1;
display: flex; display: flex;
border-radius: 5px 5px 0 0;
align-items: center; align-items: center;
padding: 0 5px;
.view-controller-menu-item { .tab-title {
height: 100%; // font-family: monospace;
aspect-ratio: 1; // font-weight: bolder;
display: flex; margin-left: 4px;
justify-content: center; width: 90px;
align-items: center; user-select: none;
cursor: pointer;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
span {
user-select: none;
cursor: pointer;
}
} }
&::before { .tab-point {
content: ''; height: 5px;
height: calc($controller-height * 0.6); aspect-ratio: 1;
width: 1px; border-radius: 66px;
border-right: 1px solid black; margin-right: 5px;
position: absolute;
left: 2px;
} }
}
.icon { .tab-control {
height: calc($controller-height * 0.7); position: absolute;
width: calc($controller-height * 0.7); right: 10px;
border-radius: 5px; display: flex;
align-items: center;
.tab-control-icon:not(:last-child) {
margin-right: 5px;
}
}
&:not(:last-child)::after {
content: '';
height: calc($controller-height * 0.6);
width: 1px;
border-right: 1px solid black;
position: absolute;
right: 0px;
}
}
}
.view-controller-menu {
position: relative;
display: flex;
align-items: center;
padding: 0 5px;
.view-controller-menu-item {
height: 100%;
aspect-ratio: 1;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
cursor: pointer; }
background-color: rgba(128, 128, 128, 0);
transition: background-color 0.3s;
&:hover { &::before {
background-color: rgba(128, 128, 128, 0.4); content: '';
} height: calc($controller-height * 0.6);
} width: 1px;
} border-right: 1px solid black;
.view-container {
position: relative;
display: flex;
// flex-direction: column;
height: calc(100% - $controller-height);
overflow-y: hidden;
overflow-x: overlay;
.view-container-item {
flex: 1;
height: 100%;
min-width: 180px;
opacity: 1;
transition: flex .25s ease, opacity .25s ease;
}
.view-container-item-hidden {
flex: 0;
min-width: 0px;
opacity: 0;
// transition-delay: opacity .25s;
// transition: opacity 5.25s ease;
}
&::-webkit-scrollbar {
position: absolute; position: absolute;
width: 4px; left: 2px;
} }
}
// 滚动条轨道 .icon {
&::-webkit-scrollbar-track { height: calc($controller-height * 0.7);
// background: rgb(239, 239, 239); width: calc($controller-height * 0.7);
border-radius: 2px; border-radius: 5px;
} display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
background-color: rgba(128, 128, 128, 0);
transition: background-color 0.3s;
// 小滑块 &:hover {
&::-webkit-scrollbar-thumb { background-color: rgba(128, 128, 128, 0.4);
background: #e0e0e0; }
// border-radius: 5px; }
} }
&::-webkit-scrollbar-thumb:hover { .view-container {
background: #999999; position: relative;
} display: flex;
} // flex-direction: column;
height: calc(100% - $controller-height);
overflow-y: hidden;
overflow-x: overlay;
.view-container-item {
flex: 1;
height: 100%;
min-width: 180px;
opacity: 1;
transition:
flex 0.25s ease,
opacity 0.25s ease;
}
.view-container-item-hidden {
flex: 0;
min-width: 0px;
opacity: 0;
// transition-delay: opacity .25s;
// transition: opacity 5.25s ease;
}
&::-webkit-scrollbar {
position: absolute;
width: 4px;
}
// 滚动条轨道
&::-webkit-scrollbar-track {
// background: rgb(239, 239, 239);
border-radius: 2px;
}
// 小滑块
&::-webkit-scrollbar-thumb {
background: #e0e0e0;
// border-radius: 5px;
}
&::-webkit-scrollbar-thumb:hover {
background: #999999;
}
}
} }
// transition动画相关 // transition动画相关
.view { .view {
.view-controller { .view-controller {
.tabs-container { .tabs-container {
.tab-move,
.tab-enter-active {
transition: all 0.2s ease;
}
.tab-move, .tab-leave-active {
.tab-enter-active { opacity: 0;
transition: all 0.2s ease; transition: none;
} }
.tab-leave-active { .tab-enter-from {
opacity: 0; opacity: 0;
transition: none; transform: translateY(-30px);
} }
.tab-enter-from { // .tab-leave-to {
opacity: 0; // opacity: 0;
transform: translateY(-30px); // transform: translateY(-80px) translateX(calc($tag-width + 10px));
} // }
// .tab-leave-to { .tab-leave-active {
// opacity: 0; position: absolute;
// transform: translateY(-80px) translateX(calc($tag-width + 10px)); }
// } }
}
.tab-leave-active { // .view-container {
position: absolute; // .page-move {
} // // transition: all 0.55s ease;
} // }
}
// .view-container { // .page-enter-active {}
// .page-move {
// // transition: all 0.55s ease;
// }
// .page-enter-active {} // .page-leave-active {
// transition: none !important;
// }
// .page-leave-active { // .page-enter-from {
// transition: none !important; // // opacity: 0;
// } // }
// .page-enter-from { // .page-leave-active {
// // opacity: 0; // display: none;
// } // position: absolute;
// }
// .page-leave-active { // }
// display: none;
// position: absolute;
// }
// }
} }
</style> </style>
+176 -136
View File
@@ -1,155 +1,195 @@
import useVirtualPages from "@/hooks/useVirtualPages"; import useVirtualPages from '@/hooks/useVirtualPages'
import VirtualDirectory, { VirtualFile } from "./VirtualDirectory"; import VirtualDirectory, { VirtualFile } from './VirtualDirectory'
import { ShallowRef, shallowRef } from "vue"; import { ShallowRef, shallowRef } from 'vue'
import { alertTipType, usePluginHooksType } from "@/types/type"; import { alertTipType, usePluginHooksType } from '@/types/type'
import VirtualPage, { VirtualPages } from "./VirtualPage"; import VirtualPage, { VirtualPages } from './VirtualPage'
import useRootVDirectory from "@/hooks/useRootVDirectory"; import useRootVDirectory from '@/hooks/useRootVDirectory'
export enum PluginGroup { export enum PluginGroup {
default = "default", default = 'default',
mainMenu = "mainMenu", mainMenu = 'mainMenu',
// 导入的时候会立即执行函数一次 // 导入的时候会立即执行函数一次
immediately = "immediately" immediately = 'immediately'
} }
export interface registerComponentOption { export interface registerComponentOption {
key: string; key: string
name: string; name: string
icon?: any; icon?: any
getComponent: () => Promise<any>; getComponent: () => Promise<any>
group?: PluginGroup[]; group?: PluginGroup[]
filter: (VDirectories: VirtualDirectory[], VFiles: VirtualFile[]) => boolean; filter: (VDirectories: VirtualDirectory[], VFiles: VirtualFile[]) => boolean
disable?: boolean; disable?: boolean
exitConfirm?: boolean; exitConfirm?: boolean
// 若为true,则只会创建一个页面,当存在已创建页面则会直接将VFile和VDir加到curr里面 // 若为true,则只会创建一个页面,当存在已创建页面则会直接将VFile和VDir加到curr里面
single?: boolean; single?: boolean
priority?: number; priority?: number
} }
export type Plugin = { export type Plugin = {
// 用于显示的名字 // 用于显示的名字
name: string; name: string
// 代表插件的icon // 代表插件的icon
icon?: ShallowRef<any>; icon?: ShallowRef<any>
// 是否禁用插件 // 是否禁用插件
disable: boolean; disable: boolean
// 插件所属的group,用于区分插件使用的场合 // 插件所属的group,用于区分插件使用的场合
group: PluginGroup[]; group: PluginGroup[]
// 插件优先级 // 插件优先级
priority: number; priority: number
// 判断在未禁用时是否可以使用这个组件 // 判断在未禁用时是否可以使用这个组件
// 使用组件即调用下面的func // 使用组件即调用下面的func
filter: (VDirectories: VirtualDirectory[], VFiles: VirtualFile[], VPages: VirtualPages) => boolean; filter: (
func: (VDirectories: VirtualDirectory[], VFiles: VirtualFile[], hooks: usePluginHooksType, ...args: any[]) => void; VDirectories: VirtualDirectory[],
}; VFiles: VirtualFile[],
VPages: VirtualPages
) => boolean
func: (
VDirectories: VirtualDirectory[],
VFiles: VirtualFile[],
hooks: usePluginHooksType,
...args: any[]
) => void
}
export default class PluginCenter { export default class PluginCenter {
constructor(globalAlertTip: alertTipType) { constructor(globalAlertTip: alertTipType) {
this.pluginsMap = {}; this.pluginsMap = {}
this.globalAlertTip = globalAlertTip; this.globalAlertTip = globalAlertTip
} }
pluginsMap: { pluginsMap: {
[key: string]: Plugin; [key: string]: Plugin
}; }
globalAlertTip: alertTipType; globalAlertTip: alertTipType
register(key: string, plugin: Plugin) { register(key: string, plugin: Plugin) {
this.pluginsMap[key] = plugin; this.pluginsMap[key] = plugin
if (plugin.group.includes(PluginGroup.immediately)) { if (plugin.group.includes(PluginGroup.immediately)) {
this.usePlugin(key, [], [], this.usePluginHook) this.usePlugin(key, [], [], this.usePluginHook)
} }
} }
deregister(key: string) { deregister(key: string) {
delete this.pluginsMap[key] delete this.pluginsMap[key]
} }
/** /**
* 便捷地注册一个组件为插件,触发时直接用新页面打开,页面名为key * 便捷地注册一个组件为插件,触发时直接用新页面打开,页面名为key
*/ */
registerComponent(option: registerComponentOption): void { registerComponent(option: registerComponentOption): void {
const { key, name, getComponent, icon, filter, group = [PluginGroup.default], disable = false, exitConfirm = false, single = false, priority = 0 } = option; const {
let _component: any; key,
const views = useVirtualPages(); name,
this.register(key, { getComponent,
name, icon,
filter, filter,
icon: shallowRef(icon), group = [PluginGroup.default],
group, disable = false,
disable, exitConfirm = false,
priority, single = false,
func: async (VDirectories: VirtualDirectory[], VFiles: VirtualFile[]) => { priority = 0
if (filter(VDirectories, VFiles) === false) { } = option
return; let _component: any
} const views = useVirtualPages()
this.register(key, {
name,
filter,
icon: shallowRef(icon),
group,
disable,
priority,
func: async (
VDirectories: VirtualDirectory[],
VFiles: VirtualFile[]
) => {
if (filter(VDirectories, VFiles) === false) {
return
}
if (_component === undefined) { if (_component === undefined) {
const setAlertTip = this.globalAlertTip(`加载 ${name} 插件中`); const setAlertTip = this.globalAlertTip(`加载 ${name} 插件中`)
_component = await getComponent(); _component = await getComponent()
setAlertTip && setAlertTip &&
setAlertTip(`加载 ${name} 插件完成`, { setAlertTip(`加载 ${name} 插件完成`, {
type: "success", type: 'success',
timeout: 2000 timeout: 2000
}); })
} }
const _findRes = views.find(_component) as VirtualPage[]; const _findRes = views.find(_component) as VirtualPage[]
if (single && _findRes.length !== 0) { if (single && _findRes.length !== 0) {
const view = _findRes[0]; const view = _findRes[0]
view.currentFiles = [...view.currentFiles, ...VFiles]; view.currentFiles = [...view.currentFiles, ...VFiles]
view.currentDirectories = [...view.currentDirectories, ...VDirectories]; view.currentDirectories = [
} else { ...view.currentDirectories,
views.push(_component, key, VDirectories, VFiles, { ...VDirectories
VirtualPageOption: { ]
exitConfirm, } else {
allowCopy: single === false views.push(_component, key, VDirectories, VFiles, {
} VirtualPageOption: {
}); exitConfirm,
} allowCopy: single === false
} }
}); })
} }
}
})
}
getUsablePlugin( getUsablePlugin(
VDirectories: VirtualDirectory[], VDirectories: VirtualDirectory[],
VFiles: VirtualFile[], VFiles: VirtualFile[],
option?: { option?: {
group?: PluginGroup[]; group?: PluginGroup[]
} }
) { ) {
const { group = [PluginGroup.default] } = option ?? {}; const { group = [PluginGroup.default] } = option ?? {}
const usableList = []; const usableList = []
const views = useVirtualPages(); const views = useVirtualPages()
for (let key of Object.keys(this.pluginsMap)) { for (let key of Object.keys(this.pluginsMap)) {
const _plugin = this.pluginsMap[key]; const _plugin = this.pluginsMap[key]
if (!_plugin.disable && _plugin.group.filter(v => group.includes(v)).length > 0 && _plugin.filter(VDirectories, VFiles, views)) { if (
usableList.push(key); !_plugin.disable &&
} _plugin.group.filter((v) => group.includes(v)).length > 0 &&
} _plugin.filter(VDirectories, VFiles, views)
const res = usableList.map(key => ({ ) {
key, usableList.push(key)
...this.pluginsMap[key] }
})); }
res.sort((a, b) => b.priority - a.priority); const res = usableList.map((key) => ({
return res; key,
} ...this.pluginsMap[key]
}))
res.sort((a, b) => b.priority - a.priority)
return res
}
get usePluginHook(): usePluginHooksType { get usePluginHook(): usePluginHooksType {
return { return {
globalAlertTip: this.globalAlertTip, globalAlertTip: this.globalAlertTip,
getViews: useVirtualPages, getViews: useVirtualPages,
getPluginCenter: () => this, getPluginCenter: () => this,
getRootVDirectory: () => useRootVDirectory() getRootVDirectory: () => useRootVDirectory()
} }
} }
usePlugin(key: string, VDirectories?: VirtualDirectory[], VFiles?: VirtualFile[], ...args: any[]): void; usePlugin(
usePlugin(key: string, VDirectories?: VirtualDirectory[], VFiles?: VirtualFile[], ...args: any[]) { key: string,
this.pluginsMap[key].func( VDirectories?: VirtualDirectory[],
VDirectories ?? [], VFiles?: VirtualFile[],
VFiles ?? [], ...args: any[]
this.usePluginHook, ): void
...args usePlugin(
); key: string,
} VDirectories?: VirtualDirectory[],
VFiles?: VirtualFile[],
...args: any[]
) {
this.pluginsMap[key].func(
VDirectories ?? [],
VFiles ?? [],
this.usePluginHook,
...args
)
}
} }
+154 -150
View File
@@ -1,165 +1,169 @@
import generateId from "@/hooks/generateId"; import generateId from '@/hooks/generateId'
import useMiaoFetchApi from "@/hooks/useMiaoFetchApi"; import useMiaoFetchApi from '@/hooks/useMiaoFetchApi'
import VirtualDirectory from "./VirtualDirectory"; import VirtualDirectory from './VirtualDirectory'
const miaoFetchApi = useMiaoFetchApi(); const miaoFetchApi = useMiaoFetchApi()
export class UploadQueueItem { export class UploadQueueItem {
constructor( constructor(
file: File, file: File,
targetDirectory: VirtualDirectory, targetDirectory: VirtualDirectory,
config?: { config?: {
onSuccess?: () => void; onSuccess?: () => void
onFailed?: () => void; onFailed?: () => void
} }
) { ) {
this.file = file; this.file = file
this.targetDirectory = targetDirectory; this.targetDirectory = targetDirectory
this.uid = generateId(); this.uid = generateId()
this.status = "waiting"; this.status = 'waiting'
this.process = 0; this.process = 0
this.onSuccess = config && config.onSuccess; this.onSuccess = config && config.onSuccess
this.onFailed = config && config.onFailed; this.onFailed = config && config.onFailed
} }
uid: number; uid: number
file: File; file: File
targetDirectory: VirtualDirectory; targetDirectory: VirtualDirectory
status: "waiting" | "uploading" | "success" | "failed"; status: 'waiting' | 'uploading' | 'success' | 'failed'
process: number; process: number
failedReason: unknown | undefined; failedReason: unknown | undefined
onSuccess?: () => void; onSuccess?: () => void
onFailed?: () => void; onFailed?: () => void
_abort: (() => void | undefined) | undefined; _abort: (() => void | undefined) | undefined
_status: Promise<any> | undefined; _status: Promise<any> | undefined
/** /**
* 开始上传文件 * 开始上传文件
*/ */
startUpload() { startUpload() {
if (this.status === "uploading") { if (this.status === 'uploading') {
return; return
} }
const { abort, response } = miaoFetchApi.upload(this.file, this.targetDirectory, { const { abort, response } = miaoFetchApi.upload(
onProcess: percent => { this.file,
this.process = percent; this.targetDirectory,
} {
}); onProcess: (percent) => {
this._abort = abort; this.process = percent
this._status = response; }
this.status = "uploading"; }
response )
.then(() => { this._abort = abort
this.status = "success"; this._status = response
this.onSuccess && this.onSuccess(); this.status = 'uploading'
this._abort = undefined; response
this._status = undefined; .then(() => {
}) this.status = 'success'
.catch(e => { this.onSuccess && this.onSuccess()
this.status = "failed"; this._abort = undefined
this.failedReason = e; this._status = undefined
this.onFailed && this.onFailed(); })
}); .catch((e) => {
} this.status = 'failed'
this.failedReason = e
this.onFailed && this.onFailed()
})
}
/** /**
* 终止上传文件 * 终止上传文件
*/ */
abortUpload() { abortUpload() {
this._abort && this._abort(); this._abort && this._abort()
this.status = "failed"; this.status = 'failed'
this.failedReason = "abort"; this.failedReason = 'abort'
} }
} }
export default class UploadQueue { export default class UploadQueue {
constructor() { constructor() {
this.uid = generateId(); this.uid = generateId()
this.queue = []; this.queue = []
this.mode = "serial"; this.mode = 'serial'
} }
uid: number; uid: number
queue: UploadQueueItem[]; queue: UploadQueueItem[]
current: UploadQueueItem | undefined; current: UploadQueueItem | undefined
// 未来再去实现,目前就是串行的 // 未来再去实现,目前就是串行的
// 好像也不用去实现 // 好像也不用去实现
mode: "serial" | "parallel"; mode: 'serial' | 'parallel'
get status() { get status() {
for (let item of this.queue) { for (let item of this.queue) {
if (item.status === "uploading") { if (item.status === 'uploading') {
return "busy"; return 'busy'
} }
} }
return "free"; return 'free'
} }
/** /**
* 获取下一个需要被上传的item * 获取下一个需要被上传的item
*/ */
get nextUplpadItem() { get nextUplpadItem() {
for (let item of this.queue) { for (let item of this.queue) {
if (item.status === "waiting") { if (item.status === 'waiting') {
return item; return item
} }
} }
} }
/** /**
* 开始串行的上传循环 * 开始串行的上传循环
*/ */
loop() { loop() {
if (this.status === "busy") { if (this.status === 'busy') {
return; return
} }
if (this.nextUplpadItem) { if (this.nextUplpadItem) {
this.nextUplpadItem.startUpload(); this.nextUplpadItem.startUpload()
} }
} }
/** /**
* 向上传文件队列输送一批新的文件 * 向上传文件队列输送一批新的文件
* @param {any} files 需要上传的文件 * @param {any} files 需要上传的文件
* @param {any} targetDirectory 目标文件夹 * @param {any} targetDirectory 目标文件夹
* @param {any} option 每个文件上传完成以后都会触发一遍的回调函数 * @param {any} option 每个文件上传完成以后都会触发一遍的回调函数
* @returns {any} * @returns {any}
*/ */
push( push(
files: File[], files: File[],
targetDirectory: VirtualDirectory, targetDirectory: VirtualDirectory,
option?: { option?: {
/** /**
* 每个文件上传完成以后都会触发一遍的回调函数 * 每个文件上传完成以后都会触发一遍的回调函数
*/ */
onFinish?: () => void; onFinish?: () => void
/** /**
* 是否立即开始上传,若否则按队列顺序一个一个上传 * 是否立即开始上传,若否则按队列顺序一个一个上传
*/ */
immediately?: boolean; immediately?: boolean
} }
) { ) {
const onFinish = option?.onFinish; const onFinish = option?.onFinish
const immediately = option?.immediately ?? false; const immediately = option?.immediately ?? false
const uploadQueue = files.map(file => { const uploadQueue = files.map((file) => {
return new UploadQueueItem(file, targetDirectory, { return new UploadQueueItem(file, targetDirectory, {
onSuccess: () => { onSuccess: () => {
this.loop(); this.loop()
onFinish && onFinish(); onFinish && onFinish()
}, },
onFailed: () => { onFailed: () => {
this.loop(); this.loop()
} }
}); })
}); })
this.queue.push(...uploadQueue); this.queue.push(...uploadQueue)
if (!immediately) { if (!immediately) {
this.loop(); this.loop()
} else { } else {
uploadQueue.forEach(item => { uploadQueue.forEach((item) => {
item.startUpload(); item.startUpload()
}); })
} }
return uploadQueue; return uploadQueue
} }
} }
+199 -199
View File
@@ -10,226 +10,226 @@ const miaoFetchApi = useMiaoFetchApi()
// const vFileMap = new Map<string, VirtualFile>() // const vFileMap = new Map<string, VirtualFile>()
export interface Tree { export interface Tree {
name: string name: string
type: 'directory' type: 'directory'
path: string path: string
stats: stats stats: stats
files: { files: {
name: string name: string
type: 'file' type: 'file'
size: number size: number
stats: stats stats: stats
url: string url: string
}[] }[]
directories: Tree[] directories: Tree[]
} }
export class VirtualFile { export class VirtualFile {
constructor(info: file, parent: VirtualDirectory) { constructor(info: file, parent: VirtualDirectory) {
this.name = info.name this.name = info.name
this.size = info.size this.size = info.size
this.stats = info.stats this.stats = info.stats
this.parent = parent this.parent = parent
this.type = 'file' this.type = 'file'
this.id = generateId() this.id = generateId()
// if (vFileMap.get(this.path) !== undefined) { // if (vFileMap.get(this.path) !== undefined) {
// throw `${this.path} is already exist` // throw `${this.path} is already exist`
// } // }
// vFileMap.set(this.path, this) // vFileMap.set(this.path, this)
} }
name: string name: string
type: 'file' type: 'file'
size: number size: number
stats: stats stats: stats
parent: VirtualDirectory parent: VirtualDirectory
id: number id: number
storage: { [key: string]: any } = {} storage: { [key: string]: any } = {}
get path() { get path() {
return `${this.parent.path}${this.name}` return `${this.parent.path}${this.name}`
} }
get url() { get url() {
return `${config.api.get}${this.parent.path}${this.name}` return `${config.api.get}${this.parent.path}${this.name}`
} }
// destroy() { // destroy() {
// vFileMap.delete(this.path) // vFileMap.delete(this.path)
// } // }
} }
class VirtualDirectory { class VirtualDirectory {
/** /**
* 除非为根节点,否则必须设置parent * 除非为根节点,否则必须设置parent
*/ */
constructor(info: directory, parent?: VirtualDirectory) { constructor(info: directory, parent?: VirtualDirectory) {
this.name = info.name this.name = info.name
this.stats = info.stats this.stats = info.stats
this.parent = parent ?? undefined this.parent = parent ?? undefined
this.id = generateId() this.id = generateId()
// if (vDirectoryMap.get(this.path) !== undefined) { // if (vDirectoryMap.get(this.path) !== undefined) {
// throw `${this.path} is already exist` // throw `${this.path} is already exist`
// } // }
// vDirectoryMap.set(this.path, this) // vDirectoryMap.set(this.path, this)
} }
// 文件夹名 // 文件夹名
name: string name: string
// 子文件 // 子文件
files: VirtualFile[] = [] files: VirtualFile[] = []
// 子目录 // 子目录
directories: VirtualDirectory[] = [] directories: VirtualDirectory[] = []
// 没啥意义,标注一下就是了 // 没啥意义,标注一下就是了
type: 'directory' = 'directory' type: 'directory' = 'directory'
// 文件夹创建时间等杂项属性 // 文件夹创建时间等杂项属性
stats: stats stats: stats
// 父文件夹 // 父文件夹
parent?: VirtualDirectory parent?: VirtualDirectory
_isUpdated: boolean = false _isUpdated: boolean = false
id: number id: number
// 用来存储一些标记信息啥的 // 用来存储一些标记信息啥的
storage: { [key: string]: any } = {} storage: { [key: string]: any } = {}
/** /**
* 获取相对于根目录的路径的层数 * 获取相对于根目录的路径的层数
* 用于目录下文件定位 * 用于目录下文件定位
* @returns {string} * @returns {string}
*/ */
get layer(): number { get layer(): number {
return this.parent ? this.parent.layer + 1 : 0 return this.parent ? this.parent.layer + 1 : 0
} }
/** /**
* 相对于根目录的路径, 如: "/", "/123/321/" * 相对于根目录的路径, 如: "/", "/123/321/"
* 用于目录下文件定位 * 用于目录下文件定位
* @returns {string} * @returns {string}
*/ */
get path(): string { get path(): string {
if (!this.parent) { if (!this.parent) {
return '/' return '/'
} }
return `${this.parent.path}${this.name}/` return `${this.parent.path}${this.name}/`
} }
/** /**
* 获取从根目录开始的按顺序的文件夹 * 获取从根目录开始的按顺序的文件夹
* @returns {VirtualDirectory[]} * @returns {VirtualDirectory[]}
*/ */
get getParents(): VirtualDirectory[] { get getParents(): VirtualDirectory[] {
if (!this.parent) { if (!this.parent) {
return [this] return [this]
} }
return [...this.parent.getParents, this] return [...this.parent.getParents, this]
} }
/** /**
* 获取当前文件夹是否已经请求过至少一次数据 * 获取当前文件夹是否已经请求过至少一次数据
*/ */
get isUpdated() { get isUpdated() {
return this._isUpdated return this._isUpdated
} }
/** /**
* 获取 layer 级父文件夹, 如getParent(1)就返回父级 * 获取 layer 级父文件夹, 如getParent(1)就返回父级
* @param {number} layer 需要跳转的层数 * @param {number} layer 需要跳转的层数
* @returns {VirtualDirectory} * @returns {VirtualDirectory}
*/ */
getParent(layer: number): VirtualDirectory { getParent(layer: number): VirtualDirectory {
if (layer <= 0 || !this.parent) { if (layer <= 0 || !this.parent) {
return this return this
} }
return this.parent.getParent(layer - 1) return this.parent.getParent(layer - 1)
} }
get tree(): Tree { get tree(): Tree {
return { return {
name: this.name, name: this.name,
type: this.type, type: this.type,
path: this.path, path: this.path,
stats: this.stats, stats: this.stats,
files: files:
this.files?.map((v) => ({ this.files?.map((v) => ({
name: v.name, name: v.name,
type: v.type, type: v.type,
size: v.size, size: v.size,
stats: v.stats, stats: v.stats,
url: v.url url: v.url
})) ?? [], })) ?? [],
directories: this.directories?.map((v) => v.tree) ?? [] directories: this.directories?.map((v) => v.tree) ?? []
} }
} }
// 时间复杂度大爆炸 // 时间复杂度大爆炸
updateContent(content: (file | directory)[]) { updateContent(content: (file | directory)[]) {
this._isUpdated = true this._isUpdated = true
const itemNames: string[] = content.map((v) => v.name) const itemNames: string[] = content.map((v) => v.name)
// 删去远程端已不存在的文件与文件夹 // 删去远程端已不存在的文件与文件夹
const _delete = (target: (VirtualFile | VirtualDirectory)[]) => { const _delete = (target: (VirtualFile | VirtualDirectory)[]) => {
let index = 0 let index = 0
while (index < target.length) { while (index < target.length) {
if (!itemNames.includes(target[index].name)) { if (!itemNames.includes(target[index].name)) {
target.splice(index, 1) target.splice(index, 1)
} else { } else {
index += 1 index += 1
}
} }
} }
const _addFile = (item: file) => { }
const nvf = const _addFile = (item: file) => {
// vFileMap.get(`${this.path}${item.name}`) ?? const nvf =
new VirtualFile(item, this) // vFileMap.get(`${this.path}${item.name}`) ??
this.files.push(nvf) new VirtualFile(item, this)
} this.files.push(nvf)
const _addDirectory = (item: directory) => { }
const nvd = const _addDirectory = (item: directory) => {
// vDirectoryMap.get(`${this.path}${item.name}/`) ?? const nvd =
new VirtualDirectory(item, this) // vDirectoryMap.get(`${this.path}${item.name}/`) ??
this.directories.push(nvd) new VirtualDirectory(item, this)
} this.directories.push(nvd)
const newFileNames: string[] = difference( }
content.filter((v) => v.type === 'file').map((v) => v.name), const newFileNames: string[] = difference(
this.files.map((v) => v.name) content.filter((v) => v.type === 'file').map((v) => v.name),
) this.files.map((v) => v.name)
const newDirectoryNames: string[] = difference( )
content.filter((v) => v.type === 'directory').map((v) => v.name), const newDirectoryNames: string[] = difference(
this.directories.map((v) => v.name) content.filter((v) => v.type === 'directory').map((v) => v.name),
) this.directories.map((v) => v.name)
_delete(this.files) )
_delete(this.directories) _delete(this.files)
// 加入新的文件与文件夹 _delete(this.directories)
for (let item of content.filter((v) => newFileNames.includes(v.name))) { // 加入新的文件与文件夹
_addFile(item as file) for (let item of content.filter((v) => newFileNames.includes(v.name))) {
} _addFile(item as file)
for (let item of content.filter((v) => }
newDirectoryNames.includes(v.name) for (let item of content.filter((v) =>
)) { newDirectoryNames.includes(v.name)
_addDirectory(item as directory) )) {
} _addDirectory(item as directory)
} }
}
hasChild(item: VirtualDirectory | VirtualFile): boolean { hasChild(item: VirtualDirectory | VirtualFile): boolean {
if (item.type === 'directory') { if (item.type === 'directory') {
return this.directories?.includes(item) ?? false return this.directories?.includes(item) ?? false
} else { } else {
return this.files?.includes(item) ?? false return this.files?.includes(item) ?? false
} }
} }
// destroy() { // destroy() {
// for(const item of [...this.files, ...this.directories]){ // for(const item of [...this.files, ...this.directories]){
// item.destroy() // item.destroy()
// } // }
// vDirectoryMap.delete(this.path) // vDirectoryMap.delete(this.path)
// } // }
/** /**
* 调用后重新向远端拉取文件夹信息并进行更新 * 调用后重新向远端拉取文件夹信息并进行更新
* @returns {void} * @returns {void}
*/ */
async update(): Promise<void> { async update(): Promise<void> {
const data: (file | directory)[] = await miaoFetchApi.get(this) const data: (file | directory)[] = await miaoFetchApi.get(this)
this.updateContent(data) this.updateContent(data)
} }
} }
export default VirtualDirectory export default VirtualDirectory
+153 -159
View File
@@ -3,184 +3,178 @@ import VirtualDirectory, { VirtualFile } from './VirtualDirectory'
import generateId from '@/hooks/generateId' import generateId from '@/hooks/generateId'
export interface VirtualPageOption { export interface VirtualPageOption {
exitConfirm?: boolean exitConfirm?: boolean
allowCopy?: boolean allowCopy?: boolean
} }
export interface ViewsPushOption { export interface ViewsPushOption {
index?: number index?: number
VirtualPageOption?: VirtualPageOption VirtualPageOption?: VirtualPageOption
} }
const getRandomWebSafeColor = (() => { const getRandomWebSafeColor = (() => {
const webSafeColors = [ const webSafeColors = ['#009900', '#999900', '#009999', '#990099', '#0000ee']
'#009900', let counter = 0
'#999900', return () => {
'#009999', const color = webSafeColors[counter % webSafeColors.length]
'#990099', counter += 1
'#0000ee' return color
] }
let counter = 0
return () => {
const color = webSafeColors[counter % webSafeColors.length]
counter += 1
return color
}
})() })()
export default class VirtualPage { export default class VirtualPage {
constructor( constructor(
component: Component, component: Component,
initObjects: { initObjects: {
name: string name: string
directories?: VirtualDirectory[] directories?: VirtualDirectory[]
files?: VirtualFile[] files?: VirtualFile[]
option?: VirtualPageOption option?: VirtualPageOption
} }
) { ) {
this.name = initObjects?.name this.name = initObjects?.name
this.component = shallowRef(component) this.component = shallowRef(component)
this.currentDirectories = initObjects?.directories ?? [] this.currentDirectories = initObjects?.directories ?? []
this.currentFiles = initObjects?.files ?? [] this.currentFiles = initObjects?.files ?? []
this.visible = true this.visible = true
this.id = generateId() this.id = generateId()
this.refreshKey = Math.random() this.refreshKey = Math.random()
this.color = getRandomWebSafeColor() this.color = getRandomWebSafeColor()
this.exitConfirm = initObjects?.option?.exitConfirm ?? false this.exitConfirm = initObjects?.option?.exitConfirm ?? false
this.allowCopy = initObjects?.option?.allowCopy ?? true this.allowCopy = initObjects?.option?.allowCopy ?? true
} }
// 页面使用的组件 // 页面使用的组件
component: Component component: Component
// 页面名 // 页面名
name: string name: string
// 是否可见 // 是否可见
visible: boolean visible: boolean
// 当前正在使用的文件夹 // 当前正在使用的文件夹
currentDirectories: VirtualDirectory[] currentDirectories: VirtualDirectory[]
// 当前正在使用的文件 // 当前正在使用的文件
currentFiles: VirtualFile[] currentFiles: VirtualFile[]
// 区分每一个页面的唯一id // 区分每一个页面的唯一id
id: number id: number
// 当refreshKey改变时需要刷新页面,目前还没接入刷新 // 当refreshKey改变时需要刷新页面,目前还没接入刷新
refreshKey: number refreshKey: number
// 为了区分,每个虚拟页面都会分配一个color,这个color会体现在tab上 // 为了区分,每个虚拟页面都会分配一个color,这个color会体现在tab上
color: string color: string
// 用于展示的title // 用于展示的title
_title?: string _title?: string
// 关闭时是否需要确认(未实现) // 关闭时是否需要确认(未实现)
exitConfirm: boolean exitConfirm: boolean
// 是否允许复制页面 // 是否允许复制页面
allowCopy: boolean allowCopy: boolean
get title() { get title() {
if (this._title) { if (this._title) {
return this._title return this._title
} }
return ( return (
this?.currentDirectories[0]?.name ?? this?.currentDirectories[0]?.name ??
this?.currentFiles[0]?.name ?? this?.currentFiles[0]?.name ??
'未命名标签' '未命名标签'
) )
} }
setTitle(title: string) { setTitle(title: string) {
this._title = title this._title = title
} }
// 切换显示状态 // 切换显示状态
switchShow() { switchShow() {
this.visible = !this.visible this.visible = !this.visible
} }
// 刷新,不过好像没有用得到的时候吧 // 刷新,不过好像没有用得到的时候吧
// 事实上也不应该用得到,因为更新应该是响应式的 // 事实上也不应该用得到,因为更新应该是响应式的
refresh() { refresh() {
this.refreshKey = Math.random() this.refreshKey = Math.random()
} }
} }
export class VirtualPages { export class VirtualPages {
constructor() { constructor() {
this._views = reactive<VirtualPage[]>([]) this._views = reactive<VirtualPage[]>([])
} }
_views: VirtualPage[] _views: VirtualPage[]
get length() { get length() {
return this._views.length return this._views.length
} }
/** /**
* 查询一个页面位于_views中的次序 * 查询一个页面位于_views中的次序
* @param {any} id 要查询的页面的id * @param {any} id 要查询的页面的id
* @returns {any} * @returns {any}
*/ */
getIndex(id: number) { getIndex(id: number) {
for (let i in this._views) { for (let i in this._views) {
if (this._views[i].id === id) { if (this._views[i].id === id) {
return parseInt(i) return parseInt(i)
} }
} }
return -1 return -1
} }
/** /**
* 根据id得到view * 根据id得到view
* @param {any} id 要查询的页面的id * @param {any} id 要查询的页面的id
*/ */
getView(id: number) { getView(id: number) {
for (let v of this._views) { for (let v of this._views) {
if (v.id === id) { if (v.id === id) {
return v return v
} }
} }
return undefined return undefined
} }
/** /**
* 推入一个新的页面 * 推入一个新的页面
*/ */
push( push(
component: Component, component: Component,
name: string, name: string,
currentDirectories?: VirtualDirectory[], currentDirectories?: VirtualDirectory[],
currentFiles?: VirtualFile[], currentFiles?: VirtualFile[],
option?: ViewsPushOption option?: ViewsPushOption
) { ) {
const { index = this.length, VirtualPageOption } = option ?? {} const { index = this.length, VirtualPageOption } = option ?? {}
this._views.splice( this._views.splice(
index, index,
0, 0,
reactive<VirtualPage>( reactive<VirtualPage>(
new VirtualPage(component, { new VirtualPage(component, {
name, name,
directories: [...(currentDirectories ?? [])], directories: [...(currentDirectories ?? [])],
files: [...(currentFiles ?? [])], files: [...(currentFiles ?? [])],
option: VirtualPageOption option: VirtualPageOption
}) })
) )
) )
} }
/** /**
* 根据次序删除一个页面 * 根据次序删除一个页面
*/ */
deleteView(index: number) { deleteView(index: number) {
this._views.splice(index, 1) this._views.splice(index, 1)
} }
/** /**
* 返回第一个使用此组件的页面 * 返回第一个使用此组件的页面
*/ */
find(component: Component) : VirtualPage[] find(component: Component): VirtualPage[]
/** /**
* 通过页面名查找 * 通过页面名查找
*/ */
find(name: string) : VirtualPage[] find(name: string): VirtualPage[]
find(input: unknown) { find(input: unknown) {
// console.log(this) // console.log(this)
if (typeof input === 'string') { if (typeof input === 'string') {
return this._views.filter(v => v.component.name === input); return this._views.filter((v) => v.component.name === input)
} else { } else {
return this._views.filter(v => v.component === input); return this._views.filter((v) => v.component === input)
} }
} }
} }
+130 -107
View File
@@ -1,36 +1,57 @@
<template> <template>
<div class="miao-message-provider" ref="rootRef"> <div
<slot></slot> class="miao-message-provider"
<transition-group name="message-fade" tag="div" class="miao-message-provider-container"> ref="rootRef"
<div class="miao-message" v-for="msg in messageList" :key="msg.id" >
:style="{ maxWidth: maxMessageWidth + 'px' }"> <slot></slot>
<n-icon class="miao-message-item" size="18" :color="msg.iconColor"> <transition-group
<component :is="msg.icon"></component> name="message-fade"
</n-icon> tag="div"
<div class="miao-message-item miao-message-item-content">{{ msg.content }}</div> class="miao-message-provider-container"
>
<div
class="miao-message"
v-for="msg in messageList"
:key="msg.id"
:style="{ maxWidth: maxMessageWidth + 'px' }"
>
<n-icon
class="miao-message-item"
size="18"
:color="msg.iconColor"
>
<component :is="msg.icon"></component>
</n-icon>
<div class="miao-message-item miao-message-item-content">
{{ msg.content }}
</div> </div>
</transition-group> </div>
</div> </transition-group>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import generateId from '@/hooks/generateId'; import generateId from '@/hooks/generateId'
import { NIcon } from 'naive-ui'; import { NIcon } from 'naive-ui'
import { computed, onMounted, ref, shallowReactive } from 'vue'; import { computed, onMounted, ref, shallowReactive } from 'vue'
import { InformationCircle, CheckmarkCircle, CloseCircle } from '@vicons/ionicons5' import {
import { AlertTipMessageOptions } from '@/types/type'; InformationCircle,
CheckmarkCircle,
CloseCircle
} from '@vicons/ionicons5'
import { AlertTipMessageOptions } from '@/types/type'
interface Message { interface Message {
icon: any, icon: any
timer: any, timer: any
iconColor: string, iconColor: string
content: string, content: string
} }
const iconMap = { const iconMap = {
'info': { icon: InformationCircle, color: 'blue' }, info: { icon: InformationCircle, color: 'blue' },
'success': { icon: CheckmarkCircle, color: 'green' }, success: { icon: CheckmarkCircle, color: 'green' },
'error': { icon: CloseCircle, color: 'red' }, error: { icon: CloseCircle, color: 'red' }
} }
const messageMap = shallowReactive<Record<string, Message | undefined>>({}) const messageMap = shallowReactive<Record<string, Message | undefined>>({})
@@ -38,107 +59,109 @@ const rootRef = ref<HTMLDivElement>()
const maxMessageWidth = ref<number>(-1) const maxMessageWidth = ref<number>(-1)
const messageList = computed(() => { const messageList = computed(() => {
return Object.keys(messageMap).map(v => ({ return Object.keys(messageMap).map((v) => ({
id: v, id: v,
...messageMap[v], ...messageMap[v]
})) }))
}) })
const alertTip = (content: string, options?: AlertTipMessageOptions) => { const alertTip = (content: string, options?: AlertTipMessageOptions) => {
let timer: any let timer: any
const { timeout = 0, type = 'info', id = generateId() } = options ?? {} const { timeout = 0, type = 'info', id = generateId() } = options ?? {}
if (timeout > 0) { if (timeout > 0) {
messageMap[id]?.timer && clearTimeout(messageMap[id]?.timer) messageMap[id]?.timer && clearTimeout(messageMap[id]?.timer)
timer = setTimeout(() => { timer = setTimeout(() => {
delete messageMap[id] delete messageMap[id]
}, timeout) }, timeout)
} }
messageMap[id] = { messageMap[id] = {
icon: iconMap[type].icon, icon: iconMap[type].icon,
iconColor: iconMap[type].color, iconColor: iconMap[type].color,
content, content,
timer timer
} }
return (newContent: string, newOptions?: AlertTipMessageOptions) => { return (newContent: string, newOptions?: AlertTipMessageOptions) => {
newOptions = newOptions ?? {} newOptions = newOptions ?? {}
newOptions.id = id newOptions.id = id
alertTip(newContent, newOptions) alertTip(newContent, newOptions)
} }
} }
onMounted(async () => { onMounted(async () => {
// const set = message('test', { timeout: 5000 }) // const set = message('test', { timeout: 5000 })
// setTimeout(() => { // setTimeout(() => {
// set('miao', { type: 'success' }) // set('miao', { type: 'success' })
// }, 1000); // }, 1000);
const observer = new ResizeObserver(entries => { const observer = new ResizeObserver((entries) => {
for (let entry of entries) { for (let entry of entries) {
maxMessageWidth.value = entry.contentRect.width * 0.8; maxMessageWidth.value = entry.contentRect.width * 0.8
} }
}); })
if (rootRef.value) { if (rootRef.value) {
observer.observe(rootRef.value); observer.observe(rootRef.value)
} }
}) })
defineExpose({ alertTip })
defineExpose({ alertTip });
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.miao-message-provider { .miao-message-provider {
width: 100%; width: 100%;
height: 100%; height: 100%;
position: relative; position: relative;
overflow: hidden; overflow: hidden;
.miao-message-provider-container { .miao-message-provider-container {
position: absolute; position: absolute;
width: 0; width: 0;
height: 0; height: 0;
left: 50%; left: 50%;
top: 30px; top: 30px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
overflow: visible; overflow: visible;
z-index: 70582140539943419; z-index: 70582140539943419;
.miao-message { .miao-message {
display: flex; display: flex;
align-items: center; align-items: center;
width: max-content; width: max-content;
background-color: rgb(249, 249, 249); background-color: rgb(249, 249, 249);
padding: 5px 10px; padding: 5px 10px;
background-color: rgb(255 255 255); background-color: rgb(255 255 255);
box-shadow: 0 3px 6px -4px rgba(0, 0, 0, .12), 0 6px 16px 0 rgba(0, 0, 0, .08), 0 9px 28px 8px rgba(0, 0, 0, .05); box-shadow:
border-radius: 5px; 0 3px 6px -4px rgba(0, 0, 0, 0.12),
user-select: none; 0 6px 16px 0 rgba(0, 0, 0, 0.08),
margin-top: 10px; 0 9px 28px 8px rgba(0, 0, 0, 0.05);
border-radius: 5px;
user-select: none;
margin-top: 10px;
.miao-message-item { .miao-message-item {
margin: 0 5px; margin: 0 5px;
} }
.miao-message-item-content { .miao-message-item-content {
white-space: pre-wrap; white-space: pre-wrap;
} }
} }
} }
.message-fade-move, .message-fade-move,
.message-fade-enter-active, .message-fade-enter-active,
.message-fade-leave-active { .message-fade-leave-active {
transition: all 0.5s ease; transition: all 0.5s ease;
} }
.message-fade-enter-from, .message-fade-enter-from,
.message-fade-leave-to { .message-fade-leave-to {
opacity: 0; opacity: 0;
transform: translateX(30px); transform: translateX(30px);
} }
.message-fade-leave-active { .message-fade-leave-active {
position: absolute; position: absolute;
} }
} }
</style> </style>
+45 -33
View File
@@ -1,26 +1,39 @@
<!-- 基于naiveui的下拉菜单实现的自定义下拉菜单 --> <!-- 基于naiveui的下拉菜单实现的自定义下拉菜单 -->
<!-- 支持长按和右键呼出下拉菜单 --> <!-- 支持长按和右键呼出下拉菜单 -->
<template> <template>
<div class="main" @contextmenu="handleContextMenu" @mouseleave="handleMainMouseLeave"> <div
<slot></slot> class="main"
</div> @contextmenu="handleContextMenu"
<n-dropdown placement="bottom-start" trigger="manual" :x="x" :y="y" :options="props.options" @mouseleave="handleMainMouseLeave"
:show="showContextMenu > 0" :on-clickoutside="onClickoutside" @select="handleSelect" @mouseleave=" >
showContextMenu -= 1" @mouseenter="showContextMenu += 1" /> <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> </template>
<script setup lang="ts"> <script setup lang="ts">
import { NDropdown } from 'naive-ui/es/dropdown'; import { NDropdown } from 'naive-ui/es/dropdown'
import { DropdownOption } from 'naive-ui/es/dropdown'; import { DropdownOption } from 'naive-ui/es/dropdown'
import { nextTick, ref } from 'vue'; import { nextTick, ref } from 'vue'
const props = defineProps<{ const props = defineProps<{
options: DropdownOption[] options: DropdownOption[]
// 长按呼出右键菜单的时延,undefined时不生效 // 长按呼出右键菜单的时延,undefined时不生效
touchTimeOut?: number touchTimeOut?: number
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
select: [key: string] select: [key: string]
}>() }>()
const x = ref(0) const x = ref(0)
@@ -30,31 +43,31 @@ const showContextMenu = ref(0)
// let timer_touch: string | number | NodeJS.Timeout | undefined // let timer_touch: string | number | NodeJS.Timeout | undefined
const onClickoutside = async () => { const onClickoutside = async () => {
showContextMenu.value = 0 showContextMenu.value = 0
} }
const handleMainMouseLeave = async () => { const handleMainMouseLeave = async () => {
setTimeout(() => { setTimeout(() => {
showContextMenu.value -= 1 showContextMenu.value -= 1
}, 20) }, 20)
// nextTick(()=>{ // nextTick(()=>{
// showContextMenu.value -= 1 // showContextMenu.value -= 1
// }) // })
} }
const handleSelect = async (key: string) => { const handleSelect = async (key: string) => {
emit('select', key) emit('select', key)
showContextMenu.value = 0 showContextMenu.value = 0
} }
const handleContextMenu = (e: MouseEvent) => { const handleContextMenu = (e: MouseEvent) => {
e.preventDefault() e.preventDefault()
showContextMenu.value = 0 showContextMenu.value = 0
nextTick().then(() => { nextTick().then(() => {
showContextMenu.value += 1 showContextMenu.value += 1
x.value = e.clientX x.value = e.clientX
y.value = e.clientY y.value = e.clientY
}) })
} }
// const handleTouchStart = (e: TouchEvent) => { // const handleTouchStart = (e: TouchEvent) => {
@@ -76,13 +89,12 @@ const handleContextMenu = (e: MouseEvent) => {
// } // }
// } // }
</script> </script>
<style> <style>
.main { .main {
width: 100%; width: 100%;
height: 100%; height: 100%;
position: relative; position: relative;
} }
</style> </style>
+17 -12
View File
@@ -1,33 +1,38 @@
<template> <template>
<div ref="divRef" @dragstart="onDs" :draggable="isDraggable"> <div
<slot></slot> ref="divRef"
</div> @dragstart="onDs"
:draggable="isDraggable"
>
<slot></slot>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from 'vue'; import { onMounted, ref } from 'vue'
// import Sortable from 'sortablejs' // import Sortable from 'sortablejs'
const props = defineProps<{ const props = defineProps<{
isDraggable: boolean isDraggable: boolean
}>() }>()
props props
const emit = defineEmits<{ const emit = defineEmits<{
onDragStart: [e: DragEvent] onDragStart: [e: DragEvent]
}>() }>()
const divRef = ref<HTMLDivElement>() const divRef = ref<HTMLDivElement>()
const onDs = (e: DragEvent) => { const onDs = (e: DragEvent) => {
emit('onDragStart', e) emit('onDragStart', e)
} }
onMounted(() => { onMounted(() => {
divRef?.value?.addEventListener('dragstart', function (ev) { divRef?.value?.addEventListener('dragstart', function (ev) {
var img = new Image(); var img = new Image()
img.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' %3E%3Cpath /%3E%3C/svg%3E"; img.src =
ev?.dataTransfer?.setDragImage(img, 0, 0); "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' %3E%3Cpath /%3E%3C/svg%3E"
}) ev?.dataTransfer?.setDragImage(img, 0, 0)
})
}) })
</script> </script>
+84 -83
View File
@@ -1,12 +1,13 @@
<template> <template>
<div <div
class="container" class="container"
@dragover="handleDragOver" @dragover="handleDragOver"
@dragleave="handleDragLeave" @dragleave="handleDragLeave"
@drop="handleDrop"> @drop="handleDrop"
<slot></slot> >
<miao-mask v-model:show="showMask"></miao-mask> <slot></slot>
</div> <miao-mask v-model:show="showMask"></miao-mask>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -17,10 +18,10 @@ import config from '@/config'
import useDataBus from '@/hooks/useDataBus' import useDataBus from '@/hooks/useDataBus'
const props = defineProps({ const props = defineProps({
disable: { disable: {
type: Boolean, type: Boolean,
default: false default: false
} }
}) })
const dataBus = useDataBus() const dataBus = useDataBus()
@@ -28,104 +29,104 @@ const dataBus = useDataBus()
const { uploadSizeLimit } = config const { uploadSizeLimit } = config
const emit = defineEmits<{ const emit = defineEmits<{
onFiles: [files: File[]] onFiles: [files: File[]]
onVirtualFiles: [vFiles: VirtualFile[]] onVirtualFiles: [vFiles: VirtualFile[]]
onVirtualDirectory: [vDirectory: VirtualDirectory[]] onVirtualDirectory: [vDirectory: VirtualDirectory[]]
}>() }>()
const showMask = ref<number>(0) const showMask = ref<number>(0)
// File類型的數據可能爲文件夾,通過FileReader進行判斷 // File類型的數據可能爲文件夾,通過FileReader進行判斷
const isFile = (file: File) => const isFile = (file: File) =>
new Promise((resolve) => { new Promise((resolve) => {
const reader = new FileReader() const reader = new FileReader()
reader.onload = () => { reader.onload = () => {
resolve(true) resolve(true)
reader.abort() reader.abort()
} }
reader.onerror = () => { reader.onerror = () => {
resolve(false) resolve(false)
reader.abort() reader.abort()
} }
reader.readAsText(file) reader.readAsText(file)
}) })
/** /**
* 只保留文件,移去文件夹 * 只保留文件,移去文件夹
* @param {File[]} files * @param {File[]} files
*/ */
const removeDirectory = async (files: File[]) => { const removeDirectory = async (files: File[]) => {
let index = 0 let index = 0
while (index < files.length) { while (index < files.length) {
const currentFile = files[index] const currentFile = files[index]
const _isFile = await isFile(currentFile) const _isFile = await isFile(currentFile)
if (_isFile) { if (_isFile) {
index += 1 index += 1
continue continue
} else { } else {
files.splice(index, 1) files.splice(index, 1)
continue continue
} }
} }
} }
const check = (event: DragEvent) => { const check = (event: DragEvent) => {
return ( return (
[ [
...(event.dataTransfer?.types?.filter(v=>v === 'Files') ?? []), ...(event.dataTransfer?.types?.filter((v) => v === 'Files') ?? []),
...(dataBus.get('dragData_vFiles') ?? []), ...(dataBus.get('dragData_vFiles') ?? []),
...(dataBus.get('dragData_vDirectory') ?? []) ...(dataBus.get('dragData_vDirectory') ?? [])
].length !== 0 ].length !== 0
) )
} }
const handleDragOver = async (event: DragEvent) => { const handleDragOver = async (event: DragEvent) => {
if (props.disable || check(event) === false) { if (props.disable || check(event) === false) {
return return
} }
event.preventDefault() event.preventDefault()
if (showMask.value === 1) { if (showMask.value === 1) {
return return
} }
showMask.value = 1 showMask.value = 1
} }
const handleDragLeave = async () => { const handleDragLeave = async () => {
showMask.value = 0 showMask.value = 0
} }
const handleDrop = async (event: DragEvent) => { const handleDrop = async (event: DragEvent) => {
if (props.disable || check(event) === false) { if (props.disable || check(event) === false) {
return return
} }
showMask.value = 0 showMask.value = 0
event.preventDefault() event.preventDefault()
event.stopPropagation() event.stopPropagation()
// todo: uploadSize的限制不應該在這裏 // todo: uploadSize的限制不應該在這裏
const files = [...(event.dataTransfer?.files ?? [])].filter( const files = [...(event.dataTransfer?.files ?? [])].filter(
(file) => file.size < uploadSizeLimit (file) => file.size < uploadSizeLimit
) )
await removeDirectory(files) await removeDirectory(files)
const virtualFiles: VirtualFile[] = dataBus.pop('dragData_vFiles') const virtualFiles: VirtualFile[] = dataBus.pop('dragData_vFiles')
const virtualDirectory: VirtualDirectory[] = dataBus.pop( const virtualDirectory: VirtualDirectory[] = dataBus.pop(
'dragData_vDirectory' 'dragData_vDirectory'
) )
// console.log({ virtualDirectory, virtualFiles }) // console.log({ virtualDirectory, virtualFiles })
if (files && files.length) { if (files && files.length) {
emit('onFiles', files) emit('onFiles', files)
} }
if (virtualFiles && virtualFiles.length) { if (virtualFiles && virtualFiles.length) {
emit('onVirtualFiles', virtualFiles) emit('onVirtualFiles', virtualFiles)
} }
if (virtualDirectory && virtualDirectory.length) { if (virtualDirectory && virtualDirectory.length) {
emit('onVirtualDirectory', virtualDirectory) emit('onVirtualDirectory', virtualDirectory)
} }
} }
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.container { .container {
width: 100%; width: 100%;
height: 100%; height: 100%;
position: relative; position: relative;
} }
</style> </style>
+100 -85
View File
@@ -1,41 +1,53 @@
<!-- 只适合用于渲染过程较为复杂的组件,不然可能得不偿失 <!-- 只适合用于渲染过程较为复杂的组件,不然可能得不偿失
这么泛用的组件,性能差点也能理解 --> 这么泛用的组件,性能差点也能理解 -->
<template> <template>
<div class="miao-lazy" ref="miaoLazyRoot" <div
:style="!show ? { minHeight: _autoHeight !== undefined ? _autoHeight : props.minHeight, minWidth, margin } : {}"> class="miao-lazy"
<slot v-if="show" /> ref="miaoLazyRoot"
</div> :style="
!show
? {
minHeight:
_autoHeight !== undefined ? _autoHeight : props.minHeight,
minWidth,
margin
}
: {}
"
>
<slot v-if="show" />
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'; import { onBeforeUnmount, onMounted, ref } from 'vue'
const props = defineProps({ const props = defineProps({
// disable: { // disable: {
// type: Boolean, // type: Boolean,
// default: false, // default: false,
// }, // },
disableLazy: { disableLazy: {
type: Boolean, type: Boolean,
default: false, default: false
}, },
// 仅在内容未加载时生效,用于占位 // 仅在内容未加载时生效,用于占位
minHeight: { minHeight: {
type: String, type: String,
default: 'none', default: 'none'
}, },
minWidth: { minWidth: {
type: String, type: String,
default: 'none', default: 'none'
}, },
margin: { margin: {
type: String, type: String,
default: 'none', default: 'none'
}, },
autoHeight: { autoHeight: {
type: Boolean, type: Boolean,
default: false default: false
} }
}) })
const miaoLazyRoot = ref<HTMLDivElement>() const miaoLazyRoot = ref<HTMLDivElement>()
@@ -45,74 +57,77 @@ const _autoHeight = ref<string>()
const show = ref<boolean>(props.disableLazy) const show = ref<boolean>(props.disableLazy)
const isVisible = (dom: HTMLDivElement) => { const isVisible = (dom: HTMLDivElement) => {
const offset = dom.getBoundingClientRect().top const offset = dom.getBoundingClientRect().top
return offset > 0 && offset < 2000 return offset > 0 && offset < 2000
} }
const { showSlot, hideSlot, clearTimer } = (() => { const { showSlot, hideSlot, clearTimer } = (() => {
let timer: any let timer: any
let timerInterval: any let timerInterval: any
const clearTimer = () => { const clearTimer = () => {
timer && clearTimeout(timer) timer && clearTimeout(timer)
timerInterval && clearInterval(timerInterval) timerInterval && clearInterval(timerInterval)
timer = undefined timer = undefined
timerInterval = undefined timerInterval = undefined
} }
const hideSlot = () => { const hideSlot = () => {
clearTimer() clearTimer()
if (props.autoHeight) { if (props.autoHeight) {
_autoHeight.value = `${miaoLazyRoot.value?.clientHeight}px` _autoHeight.value = `${miaoLazyRoot.value?.clientHeight}px`
} }
show.value = false show.value = false
} }
const showSlot = () => { const showSlot = () => {
if (show.value === true) { if (show.value === true) {
return
}
clearTimer()
// timer = setTimeout(() => {
if (!miaoLazyRoot.value || isVisible(miaoLazyRoot.value) === false) {
return
}
show.value = true
timerInterval = setInterval(() => {
if (show.value === false || miaoLazyRoot.value === undefined) {
return return
} }
clearTimer() if (isVisible(miaoLazyRoot.value) === false) {
// timer = setTimeout(() => { hideSlot()
if (!miaoLazyRoot.value || isVisible(miaoLazyRoot.value) === false) { }
return }, 1000)
} // if (props.autoHeight) {
show.value = true // nextTick(() => {
timerInterval = setInterval(() => { // console.log(miaoLazyRoot.value?.clientHeight)
if (show.value === false || miaoLazyRoot.value === undefined) { // _autoHeight.value = `${miaoLazyRoot.value?.clientHeight}px`
return // })
} // }
if (isVisible(miaoLazyRoot.value) === false) { }
hideSlot() return { showSlot, hideSlot, clearTimer }
}
}, 1000)
// if (props.autoHeight) {
// nextTick(() => {
// console.log(miaoLazyRoot.value?.clientHeight)
// _autoHeight.value = `${miaoLazyRoot.value?.clientHeight}px`
// })
// }
}
return { showSlot, hideSlot, clearTimer }
})() })()
onMounted(() => { onMounted(() => {
if (show.value === false) { if (show.value === false) {
let options = { let options = {
threshold: 0 threshold: 0
}; }
let observer: IntersectionObserver | undefined = new IntersectionObserver((entries) => { let observer: IntersectionObserver | undefined = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) { if (entries[0].isIntersecting) {
showSlot() showSlot()
// miaoLazyRoot.value && observer?.unobserve(miaoLazyRoot.value) // miaoLazyRoot.value && observer?.unobserve(miaoLazyRoot.value)
// observer = undefined // observer = undefined
} else { } else {
hideSlot() hideSlot()
} }
}, options); },
miaoLazyRoot.value && observer.observe(miaoLazyRoot.value); options
} )
miaoLazyRoot.value && observer.observe(miaoLazyRoot.value)
}
}) })
onBeforeUnmount(() => { onBeforeUnmount(() => {
clearTimer() clearTimer()
}) })
</script> </script>
+38 -32
View File
@@ -1,55 +1,61 @@
<template> <template>
<transition name="transition"> <transition name="transition">
<div class="mask-body" ref="maskBodyRef" v-show="showMask"> <div
<slot></slot> class="mask-body"
</div> ref="maskBodyRef"
</transition> v-show="showMask"
>
<slot></slot>
</div>
</transition>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref } from 'vue'; import { ref } from 'vue'
const maskBodyRef = ref<HTMLDivElement>() const maskBodyRef = ref<HTMLDivElement>()
const showMask = defineModel<boolean | number>('show', { default: false, required: true }) const showMask = defineModel<boolean | number>('show', {
default: false,
required: true
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.mask-body { .mask-body {
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 { // &-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;
} }
.transition-enter-from, .transition-enter-from,
.transition-leave-to { .transition-leave-to {
opacity: 0; opacity: 0;
} }
</style> </style>
+78 -72
View File
@@ -1,27 +1,33 @@
<template> <template>
<miao-mask v-model:show="showMask"> <miao-mask v-model:show="showMask">
<n-card class="popup-card" :title="popupConfig?.title" size="medium"> <n-card
{{ popupConfig?.content }} class="popup-card"
<n-input :title="popupConfig?.title"
class="popup-input" size="medium"
v-model:value="inputValue" >
type="text" {{ popupConfig?.content }}
v-bind="popupConfig?.inputProps" <n-input
passively-activated class="popup-input"
autofocus v-model:value="inputValue"
v-if="popupConfig?.inputProps" /> type="text"
<div class="popup-button-container"> v-bind="popupConfig?.inputProps"
<n-button passively-activated
class="popup-button-container-button" autofocus
v-for="option in popupConfig?.options" v-if="popupConfig?.inputProps"
:key="option.label" />
:type="option.type" <div class="popup-button-container">
@click="_resolve && _resolve(option.key)"> <n-button
{{ option.label }} class="popup-button-container-button"
</n-button> v-for="option in popupConfig?.options"
</div> :key="option.label"
</n-card> :type="option.type"
</miao-mask> @click="_resolve && _resolve(option.key)"
>
{{ option.label }}
</n-button>
</div>
</n-card>
</miao-mask>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref, nextTick } from 'vue' import { ref, nextTick } from 'vue'
@@ -34,43 +40,43 @@ const inputValue = ref<string>('')
const _resolve = ref() const _resolve = ref()
type popupConfigType = { type popupConfigType = {
title: string title: string
content?: string content?: string
inputValue?: string inputValue?: string
inputProps?: InputProps inputProps?: InputProps
options: { options: {
label: string label: string
key: unknown key: unknown
type: type:
| 'default' | 'default'
| 'tertiary' | 'tertiary'
| 'primary' | 'primary'
| 'success' | 'success'
| 'info' | 'info'
| 'warning' | 'warning'
| 'error' | 'error'
}[] }[]
} }
const popupConfig = ref<popupConfigType>() const popupConfig = ref<popupConfigType>()
const popup = async (config: popupConfigType) => { const popup = async (config: popupConfigType) => {
popupConfig.value = config popupConfig.value = config
inputValue.value = config.inputValue ?? '' inputValue.value = config.inputValue ?? ''
showMask.value = true showMask.value = true
const key = await new Promise((resolve: (key: unknown) => unknown) => { const key = await new Promise((resolve: (key: unknown) => unknown) => {
_resolve.value = resolve _resolve.value = resolve
}) })
const text = inputValue.value const text = inputValue.value
showMask.value = false showMask.value = false
nextTick(() => { nextTick(() => {
inputValue.value = '' inputValue.value = ''
_resolve.value = undefined _resolve.value = undefined
}) })
return { return {
text, text,
key key
} }
} }
defineExpose({ popup }) defineExpose({ popup })
@@ -78,25 +84,25 @@ defineExpose({ popup })
<style scoped lang="scss"> <style scoped lang="scss">
.popup-card { .popup-card {
width: 80%; width: 80%;
.popup-input { .popup-input {
margin-bottom: 10px; margin-bottom: 10px;
} }
.popup-button-container { .popup-button-container {
height: 100%; height: 100%;
width: 100%; width: 100%;
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
flex-wrap: wrap; flex-wrap: wrap;
.popup-button-container-button { .popup-button-container-button {
margin-top: 3px; margin-top: 3px;
&:not(:last-child) { &:not(:last-child) {
margin-right: 5px; margin-right: 5px;
} }
} }
} }
} }
</style> </style>
+17 -13
View File
@@ -1,16 +1,20 @@
const baseUrl = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : ''); const baseUrl =
window.location.protocol +
'//' +
window.location.hostname +
(window.location.port ? ':' + window.location.port : '')
export default { export default {
baseUrl, baseUrl,
uploadSizeLimit: 1024 * 1024 * 100, uploadSizeLimit: 1024 * 1024 * 100,
api: { api: {
get: '/get', get: '/get',
upload: '/upload', upload: '/upload',
delete: '/delete', delete: '/delete',
query: '/query', query: '/query',
rename: '/rename', rename: '/rename',
mkdir: '/mkdir', mkdir: '/mkdir',
cut: '/cut' cut: '/cut'
}, },
enableUpload: true enableUpload: true
} }
+6 -6
View File
@@ -1,4 +1,4 @@
import VirtualDirectory, { Tree, VirtualFile } from "@/class/VirtualDirectory"; import VirtualDirectory, { Tree, VirtualFile } from '@/class/VirtualDirectory'
/** /**
* 通过VirtualDirectory的.tree重建文件夹树 * 通过VirtualDirectory的.tree重建文件夹树
@@ -6,10 +6,10 @@ import VirtualDirectory, { Tree, VirtualFile } from "@/class/VirtualDirectory";
* @returns {any} * @returns {any}
*/ */
const buildFromTree = (data: Tree) => { const buildFromTree = (data: Tree) => {
const root = new VirtualDirectory(data) const root = new VirtualDirectory(data)
root.files = data.files?.map(v=>new VirtualFile(v, root)) root.files = data.files?.map((v) => new VirtualFile(v, root))
root.directories = data.directories?.map(v=>buildFromTree(v)) root.directories = data.directories?.map((v) => buildFromTree(v))
return root return root
} }
export default buildFromTree; export default buildFromTree
+26 -18
View File
@@ -1,20 +1,28 @@
export default function dateFormatter(date: Date, fmt: string) { export default function dateFormatter(date: Date, fmt: string) {
var o:any = { var o: any = {
"M+": date.getMonth() + 1, //月份 'M+': date.getMonth() + 1, //月份
"d+": date.getDate(), //日 'd+': date.getDate(), //日
"h+": date.getHours(), //小时 'h+': date.getHours(), //小时
"m+": date.getMinutes(), //分 'm+': date.getMinutes(), //分
"s+": date.getSeconds(), //秒 's+': date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度 'q+': Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒 S: date.getMilliseconds() //毫秒
}; }
if (/(y+)/.test(fmt)) { if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); fmt = fmt.replace(
} RegExp.$1,
for (var k in o) { (date.getFullYear() + '').substr(4 - RegExp.$1.length)
if (new RegExp("(" + k + ")").test(fmt)) { )
fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); }
} for (var k in o) {
} if (new RegExp('(' + k + ')').test(fmt)) {
return fmt; fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length == 1
? o[k]
: ('00' + o[k]).substr(('' + o[k]).length)
)
}
}
return fmt
} }
+100 -95
View File
@@ -1,109 +1,114 @@
import config from "@/config"; import config from '@/config'
const { uploadSizeLimit } = config; const { uploadSizeLimit } = config
export type dropHandlerHooks = { export type dropHandlerHooks = {
/** /**
* 仅返回小于config.ts中大小限制的文件,不会返回文件夹 * 仅返回小于config.ts中大小限制的文件,不会返回文件夹
*/ */
onDropFiles?: (files: File[]) => void; onDropFiles?: (files: File[]) => void
/** /**
* 当拖动时 * 当拖动时
*/ */
onOver?: () => void; onOver?: () => void
/** /**
* 当进入时 * 当进入时
*/ */
onEnter?: () => void; onEnter?: () => void
/** /**
* 当离开时 * 当离开时
*/ */
onLeave?: () => void; onLeave?: () => void
/** /**
* 离开或是放下时都会触发 * 离开或是放下时都会触发
* @returns {any} * @returns {any}
*/ */
onEnd?: () => void; onEnd?: () => void
}; }
const isFile = (file: File) => const isFile = (file: File) =>
new Promise(resolve => { new Promise((resolve) => {
const reader = new FileReader(); const reader = new FileReader()
reader.onload = () => { reader.onload = () => {
resolve(true); resolve(true)
reader.abort(); reader.abort()
}; }
reader.onerror = () => { reader.onerror = () => {
resolve(false); resolve(false)
reader.abort(); reader.abort()
}; }
reader.readAsText(file); reader.readAsText(file)
}); })
/** /**
* 只保留文件,移去文件夹 * 只保留文件,移去文件夹
* @param {File[]} files * @param {File[]} files
*/ */
const filesFilter = async (files: File[]) => { const filesFilter = async (files: File[]) => {
let index = 0; let index = 0
while (index < files.length) { while (index < files.length) {
const currentFile = files[index]; const currentFile = files[index]
const _isFile = await isFile(currentFile); const _isFile = await isFile(currentFile)
if (_isFile) { if (_isFile) {
index += 1; index += 1
continue; continue
} else { } else {
files.splice(index, 1); files.splice(index, 1)
continue; continue
} }
} }
}; }
export default function dropHandler(dom: HTMLDivElement, hooks?: dropHandlerHooks) { export default function dropHandler(
dom.addEventListener( dom: HTMLDivElement,
"dragenter", hooks?: dropHandlerHooks
function (e) { ) {
e.preventDefault(); dom.addEventListener(
e.stopPropagation(); 'dragenter',
hooks?.onEnter && hooks?.onEnter(); function (e) {
}, e.preventDefault()
false e.stopPropagation()
); hooks?.onEnter && hooks?.onEnter()
},
dom.addEventListener( false
"dragover", )
function (e) {
e.preventDefault(); dom.addEventListener(
e.stopPropagation(); 'dragover',
hooks?.onOver && hooks?.onOver(); function (e) {
}, e.preventDefault()
false e.stopPropagation()
); hooks?.onOver && hooks?.onOver()
},
dom.addEventListener( false
"dragleave", )
function (e) {
e.preventDefault(); dom.addEventListener(
e.stopPropagation(); 'dragleave',
hooks?.onLeave && hooks?.onLeave(); function (e) {
hooks?.onEnd && hooks.onEnd(); e.preventDefault()
}, e.stopPropagation()
false hooks?.onLeave && hooks?.onLeave()
); hooks?.onEnd && hooks.onEnd()
},
dom.addEventListener( false
"drop", )
async function (e) {
// console.log(e, e.dataTransfer?.types); dom.addEventListener(
e.preventDefault(); 'drop',
e.stopPropagation(); async function (e) {
const files = [...(e.dataTransfer?.files ?? [])].filter(file => file.size < uploadSizeLimit); // console.log(e, e.dataTransfer?.types);
await filesFilter(files); e.preventDefault()
hooks?.onDropFiles && hooks.onDropFiles(files); e.stopPropagation()
hooks?.onEnd && hooks.onEnd(); const files = [...(e.dataTransfer?.files ?? [])].filter(
}, (file) => file.size < uploadSizeLimit
false )
); await filesFilter(files)
hooks?.onDropFiles && hooks.onDropFiles(files)
hooks?.onEnd && hooks.onEnd()
},
false
)
} }
+7 -7
View File
@@ -6,11 +6,11 @@ const idList: number[] = []
* @returns {number} * @returns {number}
*/ */
export default function generateId(length?: number) { export default function generateId(length?: number) {
length || (length = 16) length || (length = 16)
let id let id
while (!id || idList.includes(id)) { while (!id || idList.includes(id)) {
id = Math.ceil(Math.random() * 10 ** 16) id = Math.ceil(Math.random() * 10 ** 16)
} }
idList.push(id) idList.push(id)
return id return id
} }
+3 -3
View File
@@ -1,6 +1,6 @@
import { alertTipType } from "@/types/type"; import { alertTipType } from '@/types/type'
import initPlugin from "./init/initPlugin"; import initPlugin from './init/initPlugin'
export default async function init(globalAlertTip: alertTipType) { export default async function init(globalAlertTip: alertTipType) {
await initPlugin(globalAlertTip) await initPlugin(globalAlertTip)
} }
+25 -21
View File
@@ -1,24 +1,28 @@
import usePluginCenter, { initPluginCenter } from "@/hooks/usePluginCenter"; import usePluginCenter, { initPluginCenter } from '@/hooks/usePluginCenter'
import { Plugin, registerComponentOption } from "@/class/PluginCenter"; import { Plugin, registerComponentOption } from '@/class/PluginCenter'
import { alertTipType, PluginExportType } from "@/types/type"; import { alertTipType, PluginExportType } from '@/types/type'
const initPlugin = async (globalAlertTip: alertTipType) => { const initPlugin = async (globalAlertTip: alertTipType) => {
initPluginCenter(globalAlertTip); initPluginCenter(globalAlertTip)
const modulesFiles = import.meta.glob("@/plugins/**/export*.ts", { eager: true }); const modulesFiles = import.meta.glob('@/plugins/**/export*.ts', {
const pluginCenter = usePluginCenter(); eager: true
for (let pluginConfig of Object.values(modulesFiles)) { })
const _config = pluginConfig as { const pluginCenter = usePluginCenter()
default: registerComponentOption | Plugin; for (let pluginConfig of Object.values(modulesFiles)) {
type: PluginExportType; const _config = pluginConfig as {
key?: string; default: registerComponentOption | Plugin
}; type: PluginExportType
const { type, key } = _config; key?: string
if (type === PluginExportType.component) { }
pluginCenter.registerComponent(_config.default as registerComponentOption); const { type, key } = _config
} else if (type === PluginExportType.default) { if (type === PluginExportType.component) {
pluginCenter.register(key as string, _config.default as Plugin); pluginCenter.registerComponent(
} _config.default as registerComponentOption
} )
}; } else if (type === PluginExportType.default) {
pluginCenter.register(key as string, _config.default as Plugin)
}
}
}
export default initPlugin; export default initPlugin
+50 -50
View File
@@ -2,63 +2,63 @@ import { NIcon } from 'naive-ui'
import { h } from 'vue' import { h } from 'vue'
export const filePicker = (() => { export const filePicker = (() => {
let _resolve: ((files: File[]) => void) | undefined let _resolve: ((files: File[]) => void) | undefined
return (option?: { accept?: 'string'; multiple: boolean }) => { return (option?: { accept?: 'string'; multiple: boolean }) => {
if (_resolve) { if (_resolve) {
_resolve([]) _resolve([])
_resolve = undefined _resolve = undefined
} }
return new Promise<File[]>((resolve) => { return new Promise<File[]>((resolve) => {
const inpEle = document.createElement('input') const inpEle = document.createElement('input')
inpEle.id = `__file_${Math.ceil(Math.random() * 100000000)}` inpEle.id = `__file_${Math.ceil(Math.random() * 100000000)}`
inpEle.type = 'file' inpEle.type = 'file'
inpEle.style.display = 'none' inpEle.style.display = 'none'
_resolve = resolve _resolve = resolve
// 文件类型限制 // 文件类型限制
// inpEle.accept="image/*" // inpEle.accept="image/*"
option?.accept && (inpEle.accept = option?.accept) option?.accept && (inpEle.accept = option?.accept)
// 多选限制 // 多选限制
option?.multiple && (inpEle.multiple = option?.multiple) option?.multiple && (inpEle.multiple = option?.multiple)
// inpEle.addEventListener("change", event => fn.call(inpEle, event, inpEle.files), { once: true }); // inpEle.addEventListener("change", event => fn.call(inpEle, event, inpEle.files), { once: true });
inpEle.addEventListener( inpEle.addEventListener(
'change', 'change',
() => { () => {
if (!inpEle.files) { if (!inpEle.files) {
return return
} }
const files: File[] = [] const files: File[] = []
let i = 0 let i = 0
while (i < inpEle.files?.length) { while (i < inpEle.files?.length) {
const _file = inpEle?.files?.item(i) const _file = inpEle?.files?.item(i)
if (_file !== null) { if (_file !== null) {
files.push(_file) files.push(_file)
} }
i += 1 i += 1
} }
resolve(files) resolve(files)
_resolve = undefined _resolve = undefined
}, },
{ once: true } { once: true }
) )
inpEle.click() inpEle.click()
}) })
} }
})() })()
export const renderIcon = (icon: any) => { export const renderIcon = (icon: any) => {
return () => { return () => {
return h(NIcon, null, { return h(NIcon, null, {
default: () => h(icon) default: () => h(icon)
}) })
} }
} }
export const sleep = async (timeout: number) => { export const sleep = async (timeout: number) => {
await new Promise(_=>setTimeout(_, timeout)) await new Promise((_) => setTimeout(_, timeout))
} }
export default { export default {
filePicker, filePicker,
renderIcon, renderIcon,
sleep sleep
} }
+21 -21
View File
@@ -1,26 +1,26 @@
import { reactive } from "vue"; import { reactive } from 'vue'
let dataStorage: { let dataStorage: {
[key: string | number] : any [key: string | number]: any
}; }
export default function useDataBus() { export default function useDataBus() {
if(dataStorage === undefined) { if (dataStorage === undefined) {
dataStorage = reactive({}) 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
}, },
pop(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
}, },
get(key: string | number) { get(key: string | number) {
const value = dataStorage[key]; const value = dataStorage[key]
return value; return value
} }
}; }
} }
+281 -252
View File
@@ -1,274 +1,303 @@
import VirtualDirectory, { VirtualFile } from "@/class/VirtualDirectory"; import VirtualDirectory, { VirtualFile } from '@/class/VirtualDirectory'
import { import {
getOption, getOption,
getResponse, getResponse,
miaoFetchConfig, miaoFetchConfig,
deleteOption, deleteOption,
uploadOption, uploadOption,
queryOption, queryOption,
renameOption, renameOption,
cutOption, cutOption,
mkdirOption, mkdirOption,
getFileOption getFileOption
} from "@/types/fetch"; } from '@/types/fetch'
import Config from "@/config"; import Config from '@/config'
import axios, { AxiosRequestConfig, AxiosResponse } from "axios"; import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
export const useMiaoFetch = (option?: miaoFetchConfig) => { export const useMiaoFetch = (option?: miaoFetchConfig) => {
const retry = option?.retry ?? 0; const retry = option?.retry ?? 0
const controller = new AbortController(); const controller = new AbortController()
let flag = true; let flag = true
return { return {
miaoFetch: async (config: AxiosRequestConfig<any>): Promise<AxiosResponse<any, any>> => { miaoFetch: async (
let counter = 0; config: AxiosRequestConfig<any>
let response: any; ): Promise<AxiosResponse<any, any>> => {
let errList = []; let counter = 0
while (flag && counter <= retry) { let response: any
try { let errList = []
response = await axios({ while (flag && counter <= retry) {
...config, try {
signal: controller.signal response = await axios({
}); ...config,
return response; signal: controller.signal
} catch (_e) { })
errList.push(_e); return response
counter += 1; } catch (_e) {
} errList.push(_e)
} counter += 1
throw errList; }
}, }
/** throw errList
* 强制终止miaoFetch },
*/ /**
abortMiaoFetch: () => { * 强制终止miaoFetch
flag = false; */
controller.abort(); abortMiaoFetch: () => {
} flag = false
}; controller.abort()
}; }
}
}
const miaoFetchApi = { const miaoFetchApi = {
/** /**
* 获取对应文件夹下的数据 * 获取对应文件夹下的数据
*/ */
async get(vDirectory: VirtualDirectory, option?: getOption): Promise<getResponse> { async get(
const { baseUrl, api } = Config; vDirectory: VirtualDirectory,
const url = `${baseUrl}${api.get}${vDirectory.path}`; option?: getOption
const retry = option?.retry ?? 0; ): Promise<getResponse> {
const { baseUrl, api } = Config
const url = `${baseUrl}${api.get}${vDirectory.path}`
const retry = option?.retry ?? 0
const { miaoFetch } = useMiaoFetch({ const { miaoFetch } = useMiaoFetch({
retry retry
}); })
const response = await miaoFetch({ const response = await miaoFetch({
url url
}); })
return response.data; return response.data
}, },
/** /**
* 获取对应文件下的数据 * 获取对应文件下的数据
*/ */
getFile(vFile: VirtualFile, option?: getFileOption) { getFile(vFile: VirtualFile, option?: getFileOption) {
// const { baseUrl, api } = Config // const { baseUrl, api } = Config
const url = vFile.url; const url = vFile.url
const retry = option?.retry ?? 0; const retry = option?.retry ?? 0
const axiosOption = option?.axiosOption ?? {}; const axiosOption = option?.axiosOption ?? {}
const { miaoFetch, abortMiaoFetch: abort } = useMiaoFetch({ const { miaoFetch, abortMiaoFetch: abort } = useMiaoFetch({
retry retry
}); })
const response = miaoFetch({ const response = miaoFetch({
url, url,
responseType: "arraybuffer", responseType: 'arraybuffer',
onDownloadProgress(progressEvent) { onDownloadProgress(progressEvent) {
option && option.onProcess && option.onProcess(progressEvent.total ? progressEvent.loaded / progressEvent.total : -1); option &&
}, option.onProcess &&
...axiosOption option.onProcess(
}); progressEvent.total
return { ? progressEvent.loaded / progressEvent.total
response: new Promise<Uint8Array>(async resolve => { : -1
resolve(new Uint8Array((await response).data)); )
}), },
abort ...axiosOption
}; })
}, return {
response: new Promise<Uint8Array>(async (resolve) => {
resolve(new Uint8Array((await response).data))
}),
abort
}
},
/** /**
* 上传单个文件到对应文件夹, 后续要将data类型改成buffer以支持分片上传 * 上传单个文件到对应文件夹, 后续要将data类型改成buffer以支持分片上传
* 正常上传文件请使用uploadQueue * 正常上传文件请使用uploadQueue
*/ */
upload(data: File, targetVDir: VirtualDirectory, option?: uploadOption) { upload(data: File, targetVDir: VirtualDirectory, option?: uploadOption) {
const { baseUrl, api } = Config; const { baseUrl, api } = Config
const url = `${baseUrl}${api.upload}${targetVDir.path}`; const url = `${baseUrl}${api.upload}${targetVDir.path}`
const retry = option?.retry ?? 0; const retry = option?.retry ?? 0
const { miaoFetch, abortMiaoFetch } = useMiaoFetch({ const { miaoFetch, abortMiaoFetch } = useMiaoFetch({
retry retry
}); })
const sizeTotal = data.size; const sizeTotal = data.size
const opType = option?.type ?? "write"; const opType = option?.type ?? 'write'
const formData = new FormData(); const formData = new FormData()
formData.append("file", data); formData.append('file', data)
// 必须这样传,不然中文乱码 // 必须这样传,不然中文乱码
formData.append("fileName", data.name); formData.append('fileName', data.name)
formData.append("operateType", opType); formData.append('operateType', opType)
return { return {
abort: () => abortMiaoFetch(), abort: () => abortMiaoFetch(),
response: new Promise<{ response: new Promise<{
message: "success" | "failed"; message: 'success' | 'failed'
error?: string; error?: string
}>(async resolve => { }>(async (resolve) => {
const response = await miaoFetch({ const response = await miaoFetch({
url, url,
method: "post", method: 'post',
data: formData, data: formData,
onUploadProgress(progressEvent) { onUploadProgress(progressEvent) {
option && option.onProcess && option.onProcess(progressEvent.loaded / sizeTotal); option &&
} option.onProcess &&
}); option.onProcess(progressEvent.loaded / sizeTotal)
resolve(response.data); }
}) })
}; resolve(response.data)
}, })
}
},
/** /**
* 在目标文件夹下创建新的文件夹 * 在目标文件夹下创建新的文件夹
*/ */
mkdir(targetVDir: VirtualDirectory, newFolderName: string, option?: mkdirOption) { mkdir(
const { baseUrl, api } = Config; targetVDir: VirtualDirectory,
const url = `${baseUrl}${api.mkdir}${targetVDir.path}`; newFolderName: string,
const { miaoFetch } = useMiaoFetch({ option?: mkdirOption
retry: option?.retry ?? 0 ) {
}); const { baseUrl, api } = Config
const url = `${baseUrl}${api.mkdir}${targetVDir.path}`
const { miaoFetch } = useMiaoFetch({
retry: option?.retry ?? 0
})
return new Promise<{ return new Promise<{
message: "success" | "failed"; message: 'success' | 'failed'
error?: string; error?: string
}>(async resolve => { }>(async (resolve) => {
const response = await miaoFetch({ const response = await miaoFetch({
url, url,
method: "post", method: 'post',
data: { data: {
folderName: newFolderName folderName: newFolderName
} }
}); })
resolve(response.data); resolve(response.data)
}); })
}, },
/** /**
* 在目标文件夹下创建新的空文件,实际上是通过upload空文件实现 * 在目标文件夹下创建新的空文件,实际上是通过upload空文件实现
*/ */
mkFile(targetVDir: VirtualDirectory, newFileName: string, option?: uploadOption) { mkFile(
const emptyBlob = new Blob([]); targetVDir: VirtualDirectory,
const emptyFile = new File([emptyBlob], newFileName, { newFileName: string,
type: "text/plain" option?: uploadOption
}); ) {
return this.upload(emptyFile, targetVDir, option); 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) { delete(target: VirtualFile | VirtualDirectory, option?: deleteOption) {
const { baseUrl, api } = Config; const { baseUrl, api } = Config
const url = `${baseUrl}${api.delete}${target.path}`; const url = `${baseUrl}${api.delete}${target.path}`
const retry = option?.retry ?? 0; const retry = option?.retry ?? 0
const { miaoFetch } = useMiaoFetch({ const { miaoFetch } = useMiaoFetch({
retry retry
}); })
return { return {
response: new Promise<{ response: new Promise<{
eventId: number; eventId: number
}>(async resolve => { }>(async (resolve) => {
const response = await miaoFetch({ const response = await miaoFetch({
url, url,
method: "post" method: 'post'
}); })
resolve(response.data); resolve(response.data)
}) })
}; }
}, },
/** /**
* 重命名对应的文件或文件夹 * 重命名对应的文件或文件夹
*/ */
rename(target: VirtualFile | VirtualDirectory, newName: string, option?: renameOption) { rename(
const { baseUrl, api } = Config; target: VirtualFile | VirtualDirectory,
const url = `${baseUrl}${api.rename}${target.path}`; newName: string,
const retry = option?.retry ?? 0; option?: renameOption
const { miaoFetch } = useMiaoFetch({ ) {
retry const { baseUrl, api } = Config
}); const url = `${baseUrl}${api.rename}${target.path}`
const retry = option?.retry ?? 0
const { miaoFetch } = useMiaoFetch({
retry
})
return { return {
response: new Promise<{ response: new Promise<{
eventId: number; eventId: number
}>(async resolve => { }>(async (resolve) => {
const response = await miaoFetch({ const response = await miaoFetch({
url, url,
method: "post", method: 'post',
data: { newName } data: { newName }
}); })
resolve(response.data); resolve(response.data)
}) })
}; }
}, },
/** /**
* 剪切文件或文件夹 * 剪切文件或文件夹
*/ */
cut(target: VirtualFile | VirtualDirectory, to: VirtualDirectory, option?: cutOption) { cut(
const newPath = to.path; target: VirtualFile | VirtualDirectory,
const { baseUrl, api } = Config; to: VirtualDirectory,
const url = `${baseUrl}${api.cut}${target.path}`; option?: cutOption
const retry = option?.retry ?? 0; ) {
const { miaoFetch } = useMiaoFetch({ const newPath = to.path
retry const { baseUrl, api } = Config
}); const url = `${baseUrl}${api.cut}${target.path}`
return { const retry = option?.retry ?? 0
response: new Promise<{ const { miaoFetch } = useMiaoFetch({
eventId: number; retry
}>(async resolve => { })
const response = await miaoFetch({ return {
url, response: new Promise<{
method: "post", eventId: number
data: { newPath } }>(async (resolve) => {
}); const response = await miaoFetch({
resolve(response.data); url,
}) method: 'post',
}; data: { newPath }
}, })
resolve(response.data)
})
}
},
/** /**
* 查询服务端操作事件的进展 * 查询服务端操作事件的进展
*/ */
query(eventId: number, option?: queryOption) { query(eventId: number, option?: queryOption) {
const { baseUrl, api } = Config; const { baseUrl, api } = Config
const url = `${baseUrl}${api.query}`; const url = `${baseUrl}${api.query}`
const retry = option?.retry ?? 0; const retry = option?.retry ?? 0
const { miaoFetch } = useMiaoFetch({ const { miaoFetch } = useMiaoFetch({
retry retry
}); })
return { return {
response: new Promise<{ response: new Promise<{
status: "process" | "success" | "failed"; status: 'process' | 'success' | 'failed'
error?: unknown; error?: unknown
}>(async resolve => { }>(async (resolve) => {
const response = await miaoFetch({ const response = await miaoFetch({
url, url,
method: "get", method: 'get',
params: { params: {
id: eventId id: eventId
} }
}); })
resolve(response.data); resolve(response.data)
}) })
}; }
} }
}; }
export default function useMiaoFetchApi() { export default function useMiaoFetchApi() {
return miaoFetchApi; return miaoFetchApi
} }
+8 -8
View File
@@ -1,15 +1,15 @@
import PluginCenter from "@/class/PluginCenter"; import PluginCenter from '@/class/PluginCenter'
import { alertTipType } from "@/types/type"; import { alertTipType } from '@/types/type'
import { reactive } from "vue"; import { reactive } from 'vue'
let pluginCenter: PluginCenter let pluginCenter: PluginCenter
export const initPluginCenter = (globalAlertTip: alertTipType) => { export const initPluginCenter = (globalAlertTip: alertTipType) => {
if(!pluginCenter) { if (!pluginCenter) {
pluginCenter = reactive(new PluginCenter(globalAlertTip)) pluginCenter = reactive(new PluginCenter(globalAlertTip))
} }
} }
export default function usePluginCenter(){ export default function usePluginCenter() {
return pluginCenter return pluginCenter
} }
+12 -12
View File
@@ -1,17 +1,17 @@
import VirtualDirectory from "@/class/VirtualDirectory"; import VirtualDirectory from '@/class/VirtualDirectory'
import { reactive } from "vue"; import { reactive } from 'vue'
const root = reactive( const root = reactive(
new VirtualDirectory({ new VirtualDirectory({
name: '根目录', name: '根目录',
stats: { stats: {
atimeMs: 0, atimeMs: 0,
birthtimeMs: 0, birthtimeMs: 0,
ctimeMs: 0, ctimeMs: 0,
mtimeMs: 0 mtimeMs: 0
} }
}) })
) )
export default function useRootVDirectory() { export default function useRootVDirectory() {
return root; return root
} }
+6 -6
View File
@@ -1,11 +1,11 @@
import UploadQueue from "@/class/UploadQueue"; import UploadQueue from '@/class/UploadQueue'
import { reactive } from "vue"; import { reactive } from 'vue'
let uploadQueue: UploadQueue let uploadQueue: UploadQueue
export default () => { export default () => {
if(uploadQueue === undefined){ if (uploadQueue === undefined) {
uploadQueue = reactive(new UploadQueue()) uploadQueue = reactive(new UploadQueue())
} }
return uploadQueue return uploadQueue
} }
+8 -8
View File
@@ -1,12 +1,12 @@
import { VirtualPages } from "@/class/VirtualPage" import { VirtualPages } from '@/class/VirtualPage'
import { Reactive, reactive } from "vue" import { Reactive, reactive } from 'vue'
let views: Reactive<VirtualPages> let views: Reactive<VirtualPages>
export default function useVirtualPages(){ export default function useVirtualPages() {
if(views === undefined) { if (views === undefined) {
// views = reactive<VirtualPage[]>([]) // views = reactive<VirtualPage[]>([])
views = reactive(new VirtualPages()) views = reactive(new VirtualPages())
} }
return views return views
} }
+11 -11
View File
@@ -1,16 +1,16 @@
import { VirtualFile } from "@/class/VirtualDirectory" import { VirtualFile } from '@/class/VirtualDirectory'
import config from "@/config" import config from '@/config'
import { usePluginHooksType } from "@/types/type" import { usePluginHooksType } from '@/types/type'
import copy2Clipboard from 'copy-to-clipboard' import copy2Clipboard from 'copy-to-clipboard'
const copy = (__: any, vFiles: VirtualFile[], hooks: usePluginHooksType) => { const copy = (__: any, vFiles: VirtualFile[], hooks: usePluginHooksType) => {
const { globalAlertTip } = hooks const { globalAlertTip } = hooks
const vFile = vFiles[0] const vFile = vFiles[0]
console.log(vFile.url) console.log(vFile.url)
copy2Clipboard(`${config.baseUrl}${vFile.url}`) copy2Clipboard(`${config.baseUrl}${vFile.url}`)
globalAlertTip(`${vFile.name}的链接已复制至剪切板`, { globalAlertTip(`${vFile.name}的链接已复制至剪切板`, {
type: 'info', type: 'info',
timeout: 2000 timeout: 2000
}) })
} }
export default copy export default copy
+24 -24
View File
@@ -1,29 +1,29 @@
import { Plugin, PluginGroup } from "@/class/PluginCenter"; import { Plugin, PluginGroup } from '@/class/PluginCenter'
import Copy from "./copy"; import Copy from './copy'
import { CopyOutline } from "@vicons/ionicons5"; import { CopyOutline } from '@vicons/ionicons5'
import { PluginExportType } from "@/types/type"; import { PluginExportType } from '@/types/type'
import { shallowRef } from "vue"; import { shallowRef } from 'vue'
const pluginConfig: Plugin = { const pluginConfig: Plugin = {
name: "复制链接", name: '复制链接',
icon: shallowRef(CopyOutline), icon: shallowRef(CopyOutline),
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vDirs.length !== 0) { if (vDirs.length !== 0) {
return false; return false
} }
if (vFiles.length !== 1) { if (vFiles.length !== 1) {
return false; return false
} }
return true; return true
}, },
disable: false, disable: false,
group: [PluginGroup.default], group: [PluginGroup.default],
func: Copy, func: Copy,
priority: -1 priority: -1
}; }
export default pluginConfig; export default pluginConfig
export const type = PluginExportType.default; export const type = PluginExportType.default
export const key = 'miaoCopy'; export const key = 'miaoCopy'
+18 -18
View File
@@ -1,23 +1,23 @@
import { Plugin, PluginGroup } from "@/class/PluginCenter"; import { Plugin, PluginGroup } from '@/class/PluginCenter'
import fullScreen from "./fullScreen"; import fullScreen from './fullScreen'
import { ExpandOutline } from "@vicons/ionicons5"; import { ExpandOutline } from '@vicons/ionicons5'
import { PluginExportType } from "@/types/type"; import { PluginExportType } from '@/types/type'
import { shallowRef } from "vue"; import { shallowRef } from 'vue'
const pluginConfig: Plugin = { const pluginConfig: Plugin = {
name: "全屏", name: '全屏',
icon: shallowRef(ExpandOutline), icon: shallowRef(ExpandOutline),
filter: () => { filter: () => {
return true; return true
}, },
disable: false, disable: false,
group: [PluginGroup.mainMenu], group: [PluginGroup.mainMenu],
func: fullScreen, func: fullScreen,
priority: -1 priority: -1
}; }
export default pluginConfig; export default pluginConfig
export const type = PluginExportType.default; export const type = PluginExportType.default
export const key = "fullScreen"; export const key = 'fullScreen'
+1 -1
View File
@@ -1,4 +1,4 @@
const fullScreen = () => { const fullScreen = () => {
document.body.requestFullscreen() document.body.requestFullscreen()
} }
export default fullScreen export default fullScreen
+39 -39
View File
@@ -3,45 +3,45 @@ import { CodeOutline } from '@vicons/ionicons5'
import { PluginExportType } from '@/types/type' import { PluginExportType } from '@/types/type'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: 'miaoCodeMirror', key: 'miaoCodeMirror',
name: '代码编辑', name: '代码编辑',
icon: CodeOutline, icon: CodeOutline,
getComponent: async () => getComponent: async () =>
(await import('@/plugins/miaoCodeMirror/miaoCodeMirror.vue')).default, (await import('@/plugins/miaoCodeMirror/miaoCodeMirror.vue')).default,
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vDirs.length !== 0) { if (vDirs.length !== 0) {
return false return false
} }
if (vFiles.length !== 1) { if (vFiles.length !== 1) {
return false return false
} }
for (let end of [ for (let end of [
'js', 'js',
'ts', 'ts',
'jsx', 'jsx',
'tsx', 'tsx',
'py', 'py',
'html', 'html',
'css', 'css',
'scss', 'scss',
'go', 'go',
'json', 'json',
'md', 'md',
'yaml', 'yaml',
'txt', 'txt',
'xml', 'xml',
'vue', 'vue',
'srt', 'srt',
'vtt', 'vtt',
'ass', 'ass',
'ssa' 'ssa'
]) { ]) {
if (vFiles[0].name.endsWith(end)) { if (vFiles[0].name.endsWith(end)) {
return true return true
} }
} }
return false return false
} }
} }
export default pluginConfig export default pluginConfig
+151 -138
View File
@@ -1,21 +1,34 @@
<template> <template>
<miao-message-provider ref="miaoMessage"> <miao-message-provider ref="miaoMessage">
<div class="codemirror-container" ref="rootRef" :class="`codemirror-container-${theme}`"> <div
<div class="codemirror-container-top"> class="codemirror-container"
<div class="codemirror-container-btn codemirror-container-btn-save" @click="handleSave"> ref="rootRef"
保存 :class="`codemirror-container-${theme}`"
</div> >
<div class="codemirror-container-btn codemirror-container-btn-save" @click="handleReset"> <div class="codemirror-container-top">
恢复到上次保存 <div
</div> class="codemirror-container-btn codemirror-container-btn-save"
@click="handleSave"
>
保存
</div> </div>
<div class="codemirror-container-main"> <div
<NScrollbar style="max-height: calc(100%)"> class="codemirror-container-btn codemirror-container-btn-save"
<codemirror v-model="codeData" :extensions="extensions" /> @click="handleReset"
</NScrollbar> >
恢复到上次保存
</div> </div>
</div> </div>
</miao-message-provider> <div class="codemirror-container-main">
<NScrollbar style="max-height: calc(100%)">
<codemirror
v-model="codeData"
:extensions="extensions"
/>
</NScrollbar>
</div>
</div>
</miao-message-provider>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -29,7 +42,7 @@ import { NScrollbar } from 'naive-ui'
const miaoFetchApi = useMiaoFetchApi() const miaoFetchApi = useMiaoFetchApi()
const currentFiles = defineModel<VirtualFile[]>('currentFiles', { const currentFiles = defineModel<VirtualFile[]>('currentFiles', {
required: true required: true
}) })
const decoder = new TextDecoder('utf-8') const decoder = new TextDecoder('utf-8')
@@ -45,31 +58,31 @@ const extensions = ref<any[]>([])
const theme = ref<'light' | 'dark'>('light') const theme = ref<'light' | 'dark'>('light')
const handleSave = async () => { const handleSave = async () => {
if (bakData.value === codeData.value || !vFile.value) { if (bakData.value === codeData.value || !vFile.value) {
miaoMessage.value?.alertTip('内容未改动', { miaoMessage.value?.alertTip('内容未改动', {
timeout: 3000, timeout: 3000,
type: 'info' type: 'info'
}) })
return return
} }
const parentDir = vFile.value?.parent const parentDir = vFile.value?.parent
const file_bak = new File( const file_bak = new File(
[new Blob([bakData.value ?? ''])], [new Blob([bakData.value ?? ''])],
`${vFile.value?.name}.bak` `${vFile.value?.name}.bak`
) )
const file = new File([new Blob([codeData.value ?? ''])], vFile.value.name) const file = new File([new Blob([codeData.value ?? ''])], vFile.value.name)
bakData.value = codeData.value bakData.value = codeData.value
const { response } = miaoFetchApi.upload(file, parentDir) const { response } = miaoFetchApi.upload(file, parentDir)
false && miaoFetchApi.upload(file_bak, parentDir) false && miaoFetchApi.upload(file_bak, parentDir)
await response await response
miaoMessage.value?.alertTip('保存成功', { miaoMessage.value?.alertTip('保存成功', {
timeout: 5000, timeout: 5000,
type: 'success' type: 'success'
}) })
} }
const handleReset = async () => { const handleReset = async () => {
codeData.value = bakData.value codeData.value = bakData.value
} }
// const switchTheme = async () => { // const switchTheme = async () => {
@@ -85,125 +98,125 @@ const handleReset = async () => {
// } // }
const getLangExtensions = async (fileName: string) => { const getLangExtensions = async (fileName: string) => {
const ext = fileName.split('.').pop()?.toLocaleLowerCase() const ext = fileName.split('.').pop()?.toLocaleLowerCase()
switch (ext) { switch (ext) {
case 'js': case 'js':
case 'jsx': case 'jsx':
case 'ts': case 'ts':
case 'tsx': case 'tsx':
const { javascript } = await import('@codemirror/lang-javascript') const { javascript } = await import('@codemirror/lang-javascript')
return [ return [
javascript({ javascript({
jsx: ext.substring(2, 3) === 'x', jsx: ext.substring(2, 3) === 'x',
typescript: ext.substring(0, 2) === 'js' typescript: ext.substring(0, 2) === 'js'
}) })
] ]
break break
case 'css': case 'css':
case 'scss': case 'scss':
const { sass } = await import('@codemirror/lang-sass') const { sass } = await import('@codemirror/lang-sass')
return [sass()] return [sass()]
break break
case 'html': case 'html':
const { html } = await import('@codemirror/lang-html') const { html } = await import('@codemirror/lang-html')
return [html()] return [html()]
break break
case 'py': case 'py':
const { python } = await import('@codemirror/lang-python') const { python } = await import('@codemirror/lang-python')
return [python()] return [python()]
break break
case 'go': case 'go':
const { go } = await import('@codemirror/lang-go') const { go } = await import('@codemirror/lang-go')
return [go()] return [go()]
break break
case 'json': case 'json':
const { json } = await import('@codemirror/lang-json') const { json } = await import('@codemirror/lang-json')
return [json()] return [json()]
break break
case 'md': case 'md':
const { markdown } = await import('@codemirror/lang-markdown') const { markdown } = await import('@codemirror/lang-markdown')
return [markdown()] return [markdown()]
break break
case 'yaml': case 'yaml':
const { yaml } = await import('@codemirror/lang-yaml') const { yaml } = await import('@codemirror/lang-yaml')
return [yaml()] return [yaml()]
break break
case 'vue': case 'vue':
const { vue } = await import('@codemirror/lang-vue') const { vue } = await import('@codemirror/lang-vue')
return [vue()] return [vue()]
break break
case 'xml': case 'xml':
const { xml } = await import('@codemirror/lang-xml') const { xml } = await import('@codemirror/lang-xml')
return [xml()] return [xml()]
break break
default: default:
return [] return []
} }
} }
onMounted(async () => { onMounted(async () => {
vFile.value = currentFiles.value[0] vFile.value = currentFiles.value[0]
const fileName = currentFiles.value[0].name const fileName = currentFiles.value[0].name
codeData.value = decoder.decode( codeData.value = decoder.decode(
await (miaoFetchApi.getFile(currentFiles.value[0], { await miaoFetchApi.getFile(currentFiles.value[0], {
axiosOption: { axiosOption: {
headers: { headers: {
'Cache-Control': 'no-cache' 'Cache-Control': 'no-cache'
}
} }
}).response) }
) }).response
bakData.value = codeData.value )
extensions.value = [...(await getLangExtensions(fileName))] bakData.value = codeData.value
extensions.value = [...(await getLangExtensions(fileName))]
rootRef.value?.addEventListener('keydown', (event) => { rootRef.value?.addEventListener('keydown', (event) => {
if (event.ctrlKey && event.key === 's') { if (event.ctrlKey && event.key === 's') {
event.preventDefault() event.preventDefault()
handleSave() handleSave()
} }
}) })
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.codemirror-container { .codemirror-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
overflow-y: hidden; overflow-y: hidden;
.codemirror-container-top { .codemirror-container-top {
height: 25px; height: 25px;
display: flex; display: flex;
border-bottom: 1px solid #000; border-bottom: 1px solid #000;
} }
.codemirror-container-btn { .codemirror-container-btn {
height: 25px; height: 25px;
padding: 0 10px; padding: 0 10px;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
cursor: pointer; cursor: pointer;
user-select: none; user-select: none;
background-color: none; background-color: none;
transition: background-color 0.25s; transition: background-color 0.25s;
&:hover { &:hover {
background-color: #e8e8e8; background-color: #e8e8e8;
} }
} }
.codemirror-container-main { .codemirror-container-main {
height: calc(100% - 25px); height: calc(100% - 25px);
position: relative; position: relative;
} }
} }
.codemirror-container-dark { .codemirror-container-dark {
background-color: rgb(30, 30, 30); background-color: rgb(30, 30, 30);
} }
.codemirror-container-light { .codemirror-container-light {
background-color: rgb(255, 255, 255); background-color: rgb(255, 255, 255);
} }
</style> </style>
+14 -15
View File
@@ -3,21 +3,20 @@ import { registerComponentOption } from '@/class/PluginCenter'
import { PluginExportType } from '@/types/type' import { PluginExportType } from '@/types/type'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: 'miaoCrypto', key: 'miaoCrypto',
name: '文件加密', name: '文件加密',
getComponent: async () => getComponent: async () => (await import('./miaoCrypto.vue')).default,
(await import('./miaoCrypto.vue')).default, filter: (vDirs, vFiles) => {
filter: (vDirs, vFiles) => { return true
return true if (vDirs.length !== 0) {
if (vDirs.length !== 0) { return false
return false }
} if (vFiles.length !== 1) {
if (vFiles.length !== 1) { return false
return false }
} return vFiles[0].name.endsWith('txt')
return vFiles[0].name.endsWith('txt') },
}, disable: true
disable: true,
} }
export default pluginConfig export default pluginConfig
+8 -8
View File
@@ -8,12 +8,12 @@ import aes_worker from '../workers/aes-worker?worker'
* @returns {Uint8Array} * @returns {Uint8Array}
*/ */
export default (key: string, data: Uint8Array) => { export default (key: string, data: Uint8Array) => {
const key_u8i = aesJs.utils.utf8.toBytes(key) const key_u8i = aesJs.utils.utf8.toBytes(key)
return new Promise<Uint8Array>((resolve) => { return new Promise<Uint8Array>((resolve) => {
const aesWorker = new aes_worker() const aesWorker = new aes_worker()
aesWorker.onmessage = (event) => { aesWorker.onmessage = (event) => {
resolve(event.data) resolve(event.data)
} }
aesWorker.postMessage({ data, key: key_u8i }) aesWorker.postMessage({ data, key: key_u8i })
}) })
} }
+159 -144
View File
@@ -1,27 +1,41 @@
<template> <template>
<miao-drop-handler @on-virtual-files="handleDropVirtualFiles"> <miao-drop-handler @on-virtual-files="handleDropVirtualFiles">
<div class="miaoCrypto-container"> <div class="miaoCrypto-container">
<div class="miaoCrypto-container-encrypt miaoCrypto-container-item"> <div class="miaoCrypto-container-encrypt miaoCrypto-container-item">
<n-scrollbar style="max-height: 100%">
<n-scrollbar style="max-height: 100%"> <div
<div v-for="item of workItemList" :key="item.id" class="miaoCrypto-container-item-item"> v-for="item of workItemList"
<div class="miaoCrypto-container-item-percentBar" :style="{ :key="item.id"
zIndex: 0, class="miaoCrypto-container-item-item"
width: item.getBufferProgress !== -1 ? `${item.getBufferProgress * 100}%` : `0%`, >
backgroundColor: 'blue' <div
}"></div> class="miaoCrypto-container-item-percentBar"
<div class="miaoCrypto-container-item-percentBar" :style="{ :style="{
zIndex: 1, zIndex: 0,
width: item.status === 'finish' ? `100%` : `0%`, width:
backgroundColor: 'green' item.getBufferProgress !== -1
}"></div> ? `${item.getBufferProgress * 100}%`
<span class="miaoCrypto-container-item-content">{{ item.name }}{{ item.status }}</span> : `0%`,
</div> backgroundColor: 'blue'
</n-scrollbar> }"
</div> ></div>
<!-- <div class="miaoCrypto-container-decrypt miaoCrypto-container-item"></div> --> <div
</div> class="miaoCrypto-container-item-percentBar"
</miao-drop-handler> :style="{
zIndex: 1,
width: item.status === 'finish' ? `100%` : `0%`,
backgroundColor: 'green'
}"
></div>
<span class="miaoCrypto-container-item-content">
{{ item.name }}{{ item.status }}
</span>
</div>
</n-scrollbar>
</div>
<!-- <div class="miaoCrypto-container-decrypt miaoCrypto-container-item"></div> -->
</div>
</miao-drop-handler>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -38,159 +52,160 @@ import { computed } from 'vue'
const miaoFetchApi = useMiaoFetchApi() const miaoFetchApi = useMiaoFetchApi()
interface workItem { interface workItem {
id: number id: number
status: 'wait' | 'process' | 'finish' | 'error' status: 'wait' | 'process' | 'finish' | 'error'
buffer?: Uint8Array buffer?: Uint8Array
getBuffer: () => Promise<Uint8Array> getBuffer: () => Promise<Uint8Array>
getBufferProgress: number getBufferProgress: number
getBufferAbort?: () => void getBufferAbort?: () => void
isGettingBuffer: boolean isGettingBuffer: boolean
name: string name: string
} }
class Work { class Work {
constructor(func: (key: string, data: Uint8Array) => Promise<Uint8Array>) { constructor(func: (key: string, data: Uint8Array) => Promise<Uint8Array>) {
this.queue = [] this.queue = []
this.func = func this.func = func
this.abortLoop = false this.abortLoop = false
} }
queue: workItem[] queue: workItem[]
func: (key: string, data: Uint8Array) => Promise<Uint8Array> func: (key: string, data: Uint8Array) => Promise<Uint8Array>
abortLoop: boolean abortLoop: boolean
get isBusy() { get isBusy() {
return this.queue.filter((v) => v.status === 'process').length > 0 return this.queue.filter((v) => v.status === 'process').length > 0
} }
async funcLoop() { async funcLoop() {
if (this.isBusy || this.abortLoop) { if (this.isBusy || this.abortLoop) {
return return
} }
const currentItem = this.queue.filter((v) => v.status === 'wait')[0] const currentItem = this.queue.filter((v) => v.status === 'wait')[0]
if (currentItem === undefined || currentItem.buffer === undefined) { if (currentItem === undefined || currentItem.buffer === undefined) {
return return
} }
currentItem.status = 'process' currentItem.status = 'process'
try { try {
currentItem.buffer = await this.func(key.value, currentItem.buffer) currentItem.buffer = await this.func(key.value, currentItem.buffer)
currentItem.status = 'finish' currentItem.status = 'finish'
} catch (e) { } catch (e) {
currentItem.status = 'error' currentItem.status = 'error'
} }
this.funcLoop() this.funcLoop()
} }
async getBufferLoop() { async getBufferLoop() {
const _list = this.queue.filter( const _list = this.queue.filter(
(v) => v.isGettingBuffer === false && v.buffer === undefined (v) => v.isGettingBuffer === false && v.buffer === undefined
) )
if (_list.length === 0 || this.abortLoop) { if (_list.length === 0 || this.abortLoop) {
return return
} }
const item = _list[0] const item = _list[0]
item.isGettingBuffer = true item.isGettingBuffer = true
try { try {
item.buffer = await item.getBuffer() item.buffer = await item.getBuffer()
} catch(e) { } catch (e) {
item.status = 'error' item.status = 'error'
} }
item.isGettingBuffer = false item.isGettingBuffer = false
this.funcLoop() this.funcLoop()
this.getBufferLoop() this.getBufferLoop()
} }
push(itemList: workItem[]) { push(itemList: workItem[]) {
this.queue.push(...itemList) this.queue.push(...itemList)
this.getBufferLoop() this.getBufferLoop()
} }
pushVFiles(itemList: VirtualFile[]) { pushVFiles(itemList: VirtualFile[]) {
this.push( this.push(
itemList.map((v) => { itemList.map((v) => {
const item: workItem = shallowReactive({ const item: workItem = shallowReactive({
id: Math.random(), id: Math.random(),
status: 'wait', status: 'wait',
name: v.name, name: v.name,
getBuffer: () => { getBuffer: () => {
const { response, abort } = miaoFetchApi.getFile(v, { const { response, abort } = miaoFetchApi.getFile(v, {
onProcess(percent) { onProcess(percent) {
item.getBufferProgress = percent item.getBufferProgress = percent
} }
}) })
item.getBufferAbort = abort item.getBufferAbort = abort
return response return response
}, },
isGettingBuffer: false, isGettingBuffer: false,
getBufferProgress: 0 getBufferProgress: 0
})
return item
}) })
) return item
} })
)
}
} }
const encryptWork = reactive(new Work(aes_ctr_worker)) const encryptWork = reactive(new Work(aes_ctr_worker))
// const decryptWork = reactive(new Work(aes_ctr_worker)) // const decryptWork = reactive(new Work(aes_ctr_worker))
const workItemList = computed(() => [ const workItemList = computed(() => [
...encryptWork.queue ...encryptWork.queue
// ...decryptWork.queue // ...decryptWork.queue
]) ])
const currentFiles = defineModel<VirtualFile[]>('currentFiles', { const currentFiles = defineModel<VirtualFile[]>('currentFiles', {
required: true required: true
}) })
const key = ref('ABlockIs16Bytes!') const key = ref('ABlockIs16Bytes!')
const handleDropVirtualFiles = (vFiles: VirtualFile[]) => { const handleDropVirtualFiles = (vFiles: VirtualFile[]) => {
encryptWork.pushVFiles(vFiles) encryptWork.pushVFiles(vFiles)
} }
onMounted(() => { onMounted(() => {
encryptWork.pushVFiles(currentFiles.value) encryptWork.pushVFiles(currentFiles.value)
}) })
onUnmounted(() => { onUnmounted(() => {
encryptWork.abortLoop = true encryptWork.abortLoop = true
encryptWork.queue.forEach(item => { encryptWork.queue.forEach((item) => {
item.getBufferAbort && item.getBufferAbort() item.getBufferAbort && item.getBufferAbort()
}) })
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.miaoCrypto-container { .miaoCrypto-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
&-item { &-item {
max-height: 100%; max-height: 100%;
flex: 1; flex: 1;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
&-item { &-item {
margin: 10px auto; margin: 10px auto;
width: 95%; width: 95%;
height: 40px; height: 40px;
background-color: #fff; background-color: #fff;
box-shadow: 0 0 15px -7px rgba(0, 0, 0, 0.1725490196), box-shadow:
0 0 3px 1px #43434359; 0 0 15px -7px rgba(0, 0, 0, 0.1725490196),
0 0 3px 1px #43434359;
border-radius: 5px;
position: relative;
.miaoCrypto-container-item-percentBar {
height: 100%;
position: absolute;
top: 0;
left: 0;
border-radius: 5px; border-radius: 5px;
}
.miaoCrypto-container-item-content {
position: relative; position: relative;
z-index: 3;
.miaoCrypto-container-item-percentBar { }
height: 100%; }
position: absolute; }
top: 0;
left: 0;
border-radius: 5px;
}
.miaoCrypto-container-item-content {
position: relative;
z-index: 3
}
}
}
} }
</style> </style>
+5 -5
View File
@@ -1,9 +1,9 @@
import aesJs from 'aes-js' import aesJs from 'aes-js'
self.onmessage = async function (event) { self.onmessage = async function (event) {
const data = event.data.data as Uint8Array const data = event.data.data as Uint8Array
const key = event.data.key as Uint8Array const key = event.data.key as Uint8Array
var aesCtr = new aesJs.ModeOfOperation.ctr(key, new aesJs.Counter(7058)) var aesCtr = new aesJs.ModeOfOperation.ctr(key, new aesJs.Counter(7058))
const encryptData = aesCtr.encrypt(data) const encryptData = aesCtr.encrypt(data)
self.postMessage(encryptData) self.postMessage(encryptData)
} }
@@ -1,55 +1,57 @@
<template> <template>
<div class="miao-directory-container-bottom" :style="{ <div
backgroundColor: class="miao-directory-container-bottom"
index % 2 === 1 ? 'rgb(61 61 61)' : 'rgb(162 162 162)' :style="{
}"> backgroundColor: index % 2 === 1 ? 'rgb(61 61 61)' : 'rgb(162 162 162)'
}"
>
<div class="container-bottom-item"> <div class="container-bottom-item">
<div class="container-bottom-item-icon"> <div class="container-bottom-item-icon">
<add-outline :style="{ <add-outline
color: :style="{
index % 2 === 0 color: index % 2 === 0 ? 'rgb(0 0 0)' : 'rgb(255 255 255)'
? 'rgb(0 0 0)' }"
: 'rgb(255 255 255)' @click="emit('add-new-item')"
}" @click="emit('add-new-item')" /> />
</div> </div>
</div> </div>
<div class="container-bottom-item"> <div class="container-bottom-item">
<div class="container-bottom-item-icon"> <div class="container-bottom-item-icon">
<cloud-upload-outline :style="{ <cloud-upload-outline
color: :style="{
index % 2 === 0 color: index % 2 === 0 ? 'rgb(0 0 0)' : 'rgb(255 255 255)'
? 'rgb(0 0 0)' }"
: 'rgb(255 255 255)' @click="emit('pick-files-upload')"
}" @click="emit('pick-files-upload')" /> />
</div> </div>
</div> </div>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { AddOutline, CloudUploadOutline } from '@vicons/ionicons5' import { AddOutline, CloudUploadOutline } from '@vicons/ionicons5'
defineProps<{ defineProps<{
index: number index: number
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
'add-new-item': [] 'add-new-item': []
'pick-files-upload': [] 'pick-files-upload': []
}>() }>()
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.miao-directory-container-bottom { .miao-directory-container-bottom {
height: 60px; height: 60px;
background-color: bisque; background-color: bisque;
display: flex; display: flex;
justify-content: space-around; 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 { .container-bottom-item {
height: 40px; height: 40px;
width: 40px; width: 40px;
display: flex; display: flex;
@@ -57,21 +59,21 @@
align-items: center; align-items: center;
.container-bottom-item-icon { .container-bottom-item-icon {
svg { svg {
width: 30px; width: 30px;
height: 30px; height: 30px;
transition: width 0.3s ease; transition: width 0.3s ease;
transition: height 0.3s ease; transition: height 0.3s ease;
cursor: pointer; cursor: pointer;
} }
&:hover { &:hover {
svg { svg {
width: 40px; width: 40px;
height: 40px; height: 40px;
} }
} }
} }
} }
} }
</style> </style>
@@ -1,71 +1,103 @@
<template> <template>
<miao-draggable-div class="miao-item" :isDraggable="!draggable" ref="itemRef" @on-drag-start="handleDragStart"> <miao-draggable-div
<miaoContextMenu :options="dropDownOptions ?? []" :touch-time-out="500" @select="handleDropdownSelect"> class="miao-item"
<div class="item-main" :class="selected ? 'item-main-selected' : ''" ref="mainRef"> :isDraggable="!draggable"
<div class="item-main-front" :style="{ backgroundColor: props.color }"></div> ref="itemRef"
<Icon class="item-main-icon" v-show="clientWidth > 250"></Icon> @on-drag-start="handleDragStart"
<div class="item-main-info"> >
<div class="item-main-info-name"> <miaoContextMenu
<Icon class="item-main-info-name-icon" v-if="clientWidth <= 250"></Icon> :options="dropDownOptions ?? []"
<n-ellipsis :style="{ maxWidth: clientWidth > 250 ? '80%' : '75%' }">{{ name }}</n-ellipsis> :touch-time-out="500"
</div> @select="handleDropdownSelect"
<div class="item-main-info-date" v-if="time"> >
{{ time }} <div
</div> class="item-main"
</div> :class="selected ? 'item-main-selected' : ''"
<miao-draggable-div class="item-main-dragBtn" :isDraggable="draggable"> ref="mainRef"
<ReorderFourOutline></ReorderFourOutline> >
</miao-draggable-div> <div
class="item-main-front"
:style="{ backgroundColor: props.color }"
></div>
<Icon
class="item-main-icon"
v-show="clientWidth > 250"
></Icon>
<div class="item-main-info">
<div class="item-main-info-name">
<Icon
class="item-main-info-name-icon"
v-if="clientWidth <= 250"
></Icon>
<n-ellipsis
:style="{ maxWidth: clientWidth > 250 ? '80%' : '75%' }"
>
{{ name }}
</n-ellipsis>
</div>
<div
class="item-main-info-date"
v-if="time"
>
{{ time }}
</div>
</div> </div>
</miaoContextMenu> <miao-draggable-div
</miao-draggable-div> class="item-main-dragBtn"
:isDraggable="draggable"
>
<ReorderFourOutline></ReorderFourOutline>
</miao-draggable-div>
</div>
</miaoContextMenu>
</miao-draggable-div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import miaoContextMenu from '@/components/miaoContextMenu.vue' import miaoContextMenu from '@/components/miaoContextMenu.vue'
import { import {
DocumentText, DocumentText,
FileTray, FileTray,
Help, Help,
Image, Image,
LogoChrome, LogoChrome,
LogoCss3, LogoCss3,
LogoJavascript, LogoJavascript,
LogoVue, LogoVue,
PlayCircle, PlayCircle,
Disc, Disc,
ReorderFourOutline, ReorderFourOutline
} from '@vicons/ionicons5' } from '@vicons/ionicons5'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue' import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import dateFormatter from '@/hooks/dateFormatter' import dateFormatter from '@/hooks/dateFormatter'
import { NEllipsis } from 'naive-ui' import { NEllipsis } from 'naive-ui'
import { DropdownOption } from 'naive-ui/es/dropdown'; import { DropdownOption } from 'naive-ui/es/dropdown'
import miaoDraggableDiv from '@/components/miaoDraggableDiv.vue' import miaoDraggableDiv from '@/components/miaoDraggableDiv.vue'
// import useMiaoFetchApi from '@/hooks/useMiaoFetchApi' // import useMiaoFetchApi from '@/hooks/useMiaoFetchApi'
// const miaoFetchApi = useMiaoFetchApi() // const miaoFetchApi = useMiaoFetchApi()
const props = defineProps<{ const props = defineProps<{
item: { item: {
name: string, name: string
type: 'directory' | 'file' type: 'directory' | 'file'
stats: { stats: {
mtimeMs: number mtimeMs: number
} }
} }
name?: string name?: string
color: string color: string
dropDownOptions?: DropdownOption[] dropDownOptions?: DropdownOption[]
selected?: boolean selected?: boolean
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
download: [] download: []
delete: [] delete: []
rename: [] rename: []
dragStart: [e: DragEvent] dragStart: [e: DragEvent]
onSelected: [] onSelected: []
plugin: [plugin: string] plugin: [plugin: string]
}>() }>()
const mainRef = ref<HTMLDivElement>() const mainRef = ref<HTMLDivElement>()
@@ -78,227 +110,224 @@ const clientWidth = ref<number>(666)
const name = props.name ?? props.item.name const name = props.name ?? props.item.name
const observer = new ResizeObserver(entries => { const observer = new ResizeObserver((entries) => {
for (let entry of entries) { for (let entry of entries) {
clientWidth.value = entry.contentRect.width; clientWidth.value = entry.contentRect.width
} }
}); })
const time = computed(() => { const time = computed(() => {
return dateFormatter( return dateFormatter(
new Date(props.item.stats.mtimeMs), new Date(props.item.stats.mtimeMs),
'yyyy-MM-dd hh:mm:ss' 'yyyy-MM-dd hh:mm:ss'
) )
}) })
// 应该将所有事件emit出去才对 // 应该将所有事件emit出去才对
const handleDropdownSelect = (key: string) => { const handleDropdownSelect = (key: string) => {
if (key === 'rename') { if (key === 'rename') {
emit('rename') emit('rename')
} else if (key === 'download') { } else if (key === 'download') {
emit('download') emit('download')
} else if (key === 'delete') { } else if (key === 'delete') {
emit('delete') emit('delete')
} else if (key === 'select') { } else if (key === 'select') {
emit('onSelected') emit('onSelected')
} else if (key.startsWith('plugin:')) { } else if (key.startsWith('plugin:')) {
const plugin = key.split(':')[1] const plugin = key.split(':')[1]
emit('plugin', plugin) emit('plugin', plugin)
} }
} }
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 ( } else if (
['txt', 'doc', 'docs', 'docx', 'xls', 'xlsx'].includes(aft) ['txt', 'doc', 'docs', 'docx', 'xls', 'xlsx'].includes(aft)
) { ) {
return DocumentText
} else if (
['mp3', 'wav', 'ape', 'acc', 'ogg', 'flac'].includes(aft)
) {
return Disc
} else if (
[
'xbm',
'tif',
'pjp',
'svgz',
'jpg',
'jpeg',
'ico',
'tiff',
'gif',
'svg',
'jfif',
'webp',
'png',
'bmp',
'pjpeg',
'avif'
].includes(aft)
) {
return Image
} else if (['mp4', 'm2v', 'mkv'].includes(aft)) {
return PlayCircle
} else if (['js', 'jsx', 'ts', 'tsx'].includes(aft)) {
return LogoJavascript
} else if (['html'].includes(aft)) {
return LogoChrome
} else if (['css', 'scss', 'less'].includes(aft)) {
return LogoCss3
} else if (['vue'].includes(aft)) {
return LogoVue
}
return DocumentText return DocumentText
} } else if (['mp3', 'wav', 'ape', 'acc', 'ogg', 'flac'].includes(aft)) {
} catch { return Disc
return Help } else if (
} [
'xbm',
'tif',
'pjp',
'svgz',
'jpg',
'jpeg',
'ico',
'tiff',
'gif',
'svg',
'jfif',
'webp',
'png',
'bmp',
'pjpeg',
'avif'
].includes(aft)
) {
return Image
} else if (['mp4', 'm2v', 'mkv'].includes(aft)) {
return PlayCircle
} else if (['js', 'jsx', 'ts', 'tsx'].includes(aft)) {
return LogoJavascript
} else if (['html'].includes(aft)) {
return LogoChrome
} else if (['css', 'scss', 'less'].includes(aft)) {
return LogoCss3
} else if (['vue'].includes(aft)) {
return LogoVue
}
return DocumentText
}
} catch {
return Help
}
}) })
const itemRef = ref() const itemRef = ref()
const handleDragStart = (e: DragEvent) => { const handleDragStart = (e: DragEvent) => {
emit('dragStart', e) emit('dragStart', e)
} }
onMounted(() => { onMounted(() => {
if (mainRef.value) { if (mainRef.value) {
observer.observe(mainRef.value); observer.observe(mainRef.value)
} }
}) })
onBeforeUnmount(() => { onBeforeUnmount(() => {
if (mainRef.value) { if (mainRef.value) {
observer.unobserve(mainRef.value); observer.unobserve(mainRef.value)
} }
}) })
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.miao-item { .miao-item {
cursor: pointer; cursor: pointer;
width: calc(100% - 20px); width: calc(100% - 20px);
// min-width: 170px; // 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 10px; margin: 10px 10px;
.item-main { .item-main {
position: relative; position: relative;
width: 100%; width: 100%;
height: 95%; height: 95%;
background-color: rgb(255, 255, 255); background-color: rgb(255, 255, 255);
border-radius: 7px; border-radius: 7px;
display: flex; display: flex;
align-items: center; align-items: center;
transition: background-color 0.3s ease; transition: background-color 0.3s ease;
overflow-x: hidden; overflow-x: hidden;
.item-main-front { .item-main-front {
height: 100%; height: 100%;
min-width: 10px; min-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 {
min-width: 30px; min-width: 30px;
margin-left: 10px; margin-left: 10px;
height: 30px; height: 30px;
width: 30px; width: 30px;
color: #00403e; color: #00403e;
transition: color 0.15s ease-out; transition: color 0.15s ease-out;
} }
.item-main-info { .item-main-info {
margin-left: 10px; margin-left: 10px;
height: 100%; height: 100%;
width: calc(100% - 10px); width: calc(100% - 10px);
display: flex;
flex-direction: column;
&-name {
position: relative;
user-select: none;
display: flex; display: flex;
flex-direction: column;
&-name {
position: relative;
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 {
user-select: none;
font-size: small;
text-wrap: nowrap;
}
}
.item-main-option {
height: 100%;
width: 20px;
position: absolute;
right: 0;
border-radius: 0 7px 7px 0;
background-color: rgba(0, 0, 0, 0);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center; align-items: center;
margin-top: 3px;
transition: background-color 0.3s; &-icon {
color: #00403e;
width: 20px;
margin-right: 5px;
transition: color 0.15s ease-out;
}
}
&-date {
user-select: none;
font-size: small;
text-wrap: nowrap;
}
}
.item-main-option {
height: 100%;
width: 20px;
position: absolute;
right: 0;
border-radius: 0 7px 7px 0;
background-color: rgba(0, 0, 0, 0);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
transition: background-color 0.3s;
.item-main-option-icon {
color: #000;
transition: color 0.15s;
}
&:hover,
&:active {
background-color: #8b8b8b;
.item-main-option-icon { .item-main-option-icon {
color: #000; color: #fff;
transition: color 0.15s;
} }
}
}
&:hover, &:hover,
&:active { &:active {
background-color: #8b8b8b; background-color: #d2d2d2;
}
}
.item-main-option-icon { .item-main-selected {
color: #fff; background-color: rgba(0, 128, 207, 0.32);
}
}
}
&:hover, &:hover {
&:active { background-color: rgba(0, 128, 207, 0.64);
background-color: #d2d2d2; }
} }
}
.item-main-selected {
background-color: rgba(0, 128, 207, 0.32);
&:hover {
background-color: rgba(0, 128, 207, 0.64);
;
}
}
} }
.item-main-dragBtn { .item-main-dragBtn {
width: 20px; width: 20px;
height: 20px; height: 20px;
position: absolute; position: absolute;
right: 5px; right: 5px;
} }
</style> </style>
@@ -1,46 +1,54 @@
<template> <template>
<div <div
class="miao-directory-container-items" class="miao-directory-container-items"
:style="{ :style="{
backgroundColor: index % 2 === 0 ? '#f8f8f8' : 'rgb(240 240 240)' backgroundColor: index % 2 === 0 ? '#f8f8f8' : 'rgb(240 240 240)'
}"> }"
<n-scrollbar ref="scrollbarRef" style="max-height: 100%"> >
<miao-lazy-div <n-scrollbar
v-for="dir in showData_directory" ref="scrollbarRef"
:key="dir.id" style="max-height: 100%"
min-height="50px" >
margin="10px"> <miao-lazy-div
<miaoDirectoryItem v-for="dir in showData_directory"
:item="dir" :key="dir.id"
:color="props.color" min-height="50px"
:selected="selectedItem.includes(dir)" margin="10px"
:drop-down-options="itemDropDownOptions(dir).value" >
@delete="handleItemDelete(dir)" <miaoDirectoryItem
@plugin="(p) => handleItemUsePlugin(dir)(p)" :item="dir"
@click="handleItemClick(dir)" :color="props.color"
@drag-start="(e) => handleItemDragStart(dir)(e)" :selected="selectedItem.includes(dir)"
@rename="handleItemRename(dir)" :drop-down-options="itemDropDownOptions(dir).value"
@on-selected="handleItemSelect(dir)" /> @delete="handleItemDelete(dir)"
</miao-lazy-div> @plugin="(p) => handleItemUsePlugin(dir)(p)"
<miao-lazy-div @click="handleItemClick(dir)"
v-for="file in showData_files" @drag-start="(e) => handleItemDragStart(dir)(e)"
:key="file.id" @rename="handleItemRename(dir)"
min-height="50px"> @on-selected="handleItemSelect(dir)"
<miaoDirectoryItem />
:item="file" </miao-lazy-div>
:color="props.color" <miao-lazy-div
:selected="selectedItem.includes(file)" v-for="file in showData_files"
:drop-down-options="itemDropDownOptions(file).value" :key="file.id"
@click="handleItemClick(file)" min-height="50px"
@download="handleItemDownload(file)" >
@delete="handleItemDelete(file)" <miaoDirectoryItem
@drag-start="(e) => handleItemDragStart(file)(e)" :item="file"
@rename="handleItemRename(file)" :color="props.color"
@plugin="(p) => handleItemUsePlugin(file)(p)" :selected="selectedItem.includes(file)"
@on-selected="handleItemSelect(file)" /> :drop-down-options="itemDropDownOptions(file).value"
</miao-lazy-div> @click="handleItemClick(file)"
</n-scrollbar> @download="handleItemDownload(file)"
</div> @delete="handleItemDelete(file)"
@drag-start="(e) => handleItemDragStart(file)(e)"
@rename="handleItemRename(file)"
@plugin="(p) => handleItemUsePlugin(file)(p)"
@on-selected="handleItemSelect(file)"
/>
</miao-lazy-div>
</n-scrollbar>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -55,128 +63,128 @@ import { renderIcon } from '@/hooks/miaoTools'
const pluginCenter = usePluginCenter() const pluginCenter = usePluginCenter()
const props = defineProps<{ const props = defineProps<{
color: string color: string
index: number index: number
showData_directory: VirtualDirectory[] showData_directory: VirtualDirectory[]
showData_files: VirtualFile[] showData_files: VirtualFile[]
selectedItem: (VirtualFile | VirtualDirectory)[] selectedItem: (VirtualFile | VirtualDirectory)[]
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
'item-click': [item: VirtualDirectory | VirtualFile] 'item-click': [item: VirtualDirectory | VirtualFile]
'item-download': [item: VirtualFile] 'item-download': [item: VirtualFile]
'item-delete': [item: VirtualDirectory | VirtualFile] 'item-delete': [item: VirtualDirectory | VirtualFile]
'item-drag-start': [_event: DragEvent, item: VirtualDirectory | VirtualFile] 'item-drag-start': [_event: DragEvent, item: VirtualDirectory | VirtualFile]
'item-rename': [item: VirtualDirectory | VirtualFile] 'item-rename': [item: VirtualDirectory | VirtualFile]
'item-select': [item: VirtualDirectory | VirtualFile] 'item-select': [item: VirtualDirectory | VirtualFile]
}>() }>()
const scrollbarRef = ref() const scrollbarRef = ref()
const itemDropDownOptions = (item: VirtualDirectory | VirtualFile) => const itemDropDownOptions = (item: VirtualDirectory | VirtualFile) =>
computed(() => { computed(() => {
const items = [...props.selectedItem] const items = [...props.selectedItem]
const selected = props.selectedItem.includes(item) const selected = props.selectedItem.includes(item)
if (!selected) { if (!selected) {
items.push(item) items.push(item)
} }
const vDirs = items.filter((v) => v.type === 'directory') const vDirs = items.filter((v) => v.type === 'directory')
const vFiles = items.filter((v) => v.type === 'file') const vFiles = items.filter((v) => v.type === 'file')
const options = [ const options = [
{ {
label: '重命名', label: '重命名',
key: 'rename' key: 'rename'
}, },
{ {
label: '删除', label: '删除',
key: 'delete' key: 'delete'
} }
] ]
if (item.type === 'file') { if (item.type === 'file') {
options.push( options.push(
...[ ...[
{ {
label: '下载', label: '下载',
key: 'download' key: 'download'
} }
] ]
) )
} }
if (selected === false) { if (selected === false) {
options.push( options.push(
...[ ...[
{ {
label: '多选:选择', label: '多选:选择',
key: 'select' key: 'select'
} }
] ]
) )
} else { } else {
options.push( options.push(
...[ ...[
{ {
label: '多选:取消', label: '多选:取消',
key: 'select' key: 'select'
} }
] ]
) )
} }
options.push( options.push(
...pluginCenter.getUsablePlugin(vDirs, vFiles).map((v) => ({ ...pluginCenter.getUsablePlugin(vDirs, vFiles).map((v) => ({
label: `插件:${v.name}`, label: `插件:${v.name}`,
key: `plugin:${v.key}`, key: `plugin:${v.key}`,
icon: v.icon ? renderIcon(v.icon) : undefined icon: v.icon ? renderIcon(v.icon) : undefined
})) }))
) )
return options return options
}) })
const handleItemClick = (item: VirtualDirectory | VirtualFile) => { const handleItemClick = (item: VirtualDirectory | VirtualFile) => {
emit('item-click', item) emit('item-click', item)
} }
const handleItemDownload = (item: VirtualFile) => { const handleItemDownload = (item: VirtualFile) => {
emit('item-download', item) emit('item-download', item)
} }
const handleItemDelete = (item: VirtualDirectory | VirtualFile) => { const handleItemDelete = (item: VirtualDirectory | VirtualFile) => {
emit('item-delete', item) emit('item-delete', item)
} }
const handleItemDragStart = const handleItemDragStart =
(item: VirtualDirectory | VirtualFile) => (_event: DragEvent) => { (item: VirtualDirectory | VirtualFile) => (_event: DragEvent) => {
emit('item-drag-start', _event, item) emit('item-drag-start', _event, item)
} }
const handleItemRename = (item: VirtualDirectory | VirtualFile) => { const handleItemRename = (item: VirtualDirectory | VirtualFile) => {
emit('item-rename', item) emit('item-rename', item)
} }
const handleItemSelect = (item: VirtualDirectory | VirtualFile) => { const handleItemSelect = (item: VirtualDirectory | VirtualFile) => {
emit('item-select', item) emit('item-select', item)
} }
const handleItemUsePlugin = const handleItemUsePlugin =
(item: VirtualDirectory | VirtualFile) => (plugin: string) => { (item: VirtualDirectory | VirtualFile) => (plugin: string) => {
const items = [...props.selectedItem] const items = [...props.selectedItem]
const selected = props.selectedItem.includes(item) const selected = props.selectedItem.includes(item)
if (!selected) { if (!selected) {
items.push(item) items.push(item)
} }
const vDirs = items.filter((v) => v.type === 'directory') const vDirs = items.filter((v) => v.type === 'directory')
const vFiles = items.filter((v) => v.type === 'file') const vFiles = items.filter((v) => v.type === 'file')
pluginCenter.usePlugin(plugin, vDirs, vFiles) pluginCenter.usePlugin(plugin, vDirs, vFiles)
} }
defineExpose({ defineExpose({
scrollTo: (...args: any) => scrollbarRef.value.scrollTo(...args) scrollTo: (...args: any) => scrollbarRef.value.scrollTo(...args)
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.miao-directory-container-items { .miao-directory-container-items {
width: 100%; width: 100%;
flex: 1; flex: 1;
min-height: 0; min-height: 0;
} }
</style> </style>
@@ -1,152 +1,176 @@
<template> <template>
<div class="miao-directory-container-top" :style="{ <div
backgroundColor: class="miao-directory-container-top"
index % 2 === 0 ? '#f8f8f8' : 'rgb(240 240 240)' :style="{
}"> 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-container"> <div
<n-breadcrumb separator=">" style="margin-left: 5px"> class="container-top-colorfulBar"
<n-breadcrumb-item :clickable="false"> :style="{ backgroundColor: props.color }"
<n-icon size="18"> ></div>
<CloudOutline /> <div class="container-top-breadcrumb">
</n-icon> <div class="container-top-breadcrumb-container">
</n-breadcrumb-item> <n-breadcrumb
<n-breadcrumb-item v-for="dir in currentDirectory?.getParents" separator=">"
@click="handleClickBreadcrumbItem(dir)" :clickable="true"> style="margin-left: 5px"
<div>{{ dir.name }}</div> >
</n-breadcrumb-item> <n-breadcrumb-item :clickable="false">
</n-breadcrumb> <n-icon size="18">
</div> <CloudOutline />
</div> </n-icon>
<div class="container-top-tools"> </n-breadcrumb-item>
<n-icon class="container-top-tools-item" size="15" @click="$emit('back')"> <n-breadcrumb-item
<ChevronBackOutline /> v-for="dir in currentDirectory?.getParents"
@click="handleClickBreadcrumbItem(dir)"
:clickable="true"
>
<div>{{ dir.name }}</div>
</n-breadcrumb-item>
</n-breadcrumb>
</div>
</div>
<div class="container-top-tools">
<n-icon
class="container-top-tools-item"
size="15"
@click="$emit('back')"
>
<ChevronBackOutline />
</n-icon>
<n-icon
class="container-top-tools-item"
size="14"
@click="$emit('reload')"
>
<ReloadOutline class="container-top-tools-item-reload" />
</n-icon>
<n-dropdown
trigger="click"
:options="openMenuOption"
@select="(key: string) => emit('menuSelect', key)"
>
<n-icon
class="container-top-tools-item"
size="14"
>
<EllipsisVertical />
</n-icon> </n-icon>
<n-icon class="container-top-tools-item" size="14" @click="$emit('reload')"> </n-dropdown>
<ReloadOutline class="container-top-tools-item-reload" /> </div>
</n-icon> </div>
<n-dropdown trigger="click" :options="openMenuOption" @select="(key: string) => emit('menuSelect', key)">
<n-icon class="container-top-tools-item" size="14">
<EllipsisVertical />
</n-icon>
</n-dropdown>
</div>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { NBreadcrumbItem, NBreadcrumb, NIcon, NDropdown } from 'naive-ui' import { NBreadcrumbItem, NBreadcrumb, NIcon, NDropdown } from 'naive-ui'
import { import {
CloudOutline, CloudOutline,
ChevronBackOutline, ChevronBackOutline,
ReloadOutline, ReloadOutline,
EllipsisVertical, EllipsisVertical
} from '@vicons/ionicons5' } from '@vicons/ionicons5'
import VirtualDirectory from '@/class/VirtualDirectory' import VirtualDirectory from '@/class/VirtualDirectory'
const props = defineProps<{ const props = defineProps<{
color: string; color: string
index: number index: number
currentDirectory: VirtualDirectory | undefined; currentDirectory: VirtualDirectory | undefined
openMenuOption: { openMenuOption: {
key: string, key: string
label: string, label: string
[key: string]: any, [key: string]: any
}[] }[]
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
back: [], back: []
reload: [], reload: []
menuSelect: [key: string] menuSelect: [key: string]
'set-current-directory': [virtualDirectory: VirtualDirectory] 'set-current-directory': [virtualDirectory: VirtualDirectory]
}>() }>()
const handleClickBreadcrumbItem = (virtualDirectory: VirtualDirectory) => { const handleClickBreadcrumbItem = (virtualDirectory: VirtualDirectory) => {
emit('set-current-directory', virtualDirectory) emit('set-current-directory', virtualDirectory)
} }
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.miao-directory-container-top { .miao-directory-container-top {
height: 30px; height: 30px;
width: 100%; width: 100%;
user-select: none; user-select: none;
position: relative; position: relative;
display: flex; display: flex;
align-items: center; align-items: center;
overflow: hidden; overflow: hidden;
background-color: #f1f1f1; background-color: #f1f1f1;
.container-top-colorfulBar { .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%;
width: calc(100% - 95px); width: calc(100% - 95px);
display: flex; display: flex;
justify-content: flex-start; justify-content: flex-start;
align-items: center; align-items: center;
// overflow: hidden; // overflow: hidden;
overflow-y: hidden; overflow-y: hidden;
overflow-x: hidden; overflow-x: hidden;
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%;
right: 0; right: 0;
top: 0; top: 0;
min-width: 100%; min-width: 100%;
display: flex; display: flex;
justify-content: flex-start; justify-content: flex-start;
align-items: center; align-items: center;
} }
} }
.container-top-tools { .container-top-tools {
position: relative; position: relative;
height: 100%; height: 100%;
// width: 70px; // width: 70px;
padding: 0 5px; padding: 0 5px;
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;
margin: 0 1px; margin: 0 1px;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
background-color: #ffffff00; background-color: #ffffff00;
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);
} }
} }
}
}
} }
</style> </style>
+11 -12
View File
@@ -3,21 +3,20 @@ import FileTray from '@vicons/ionicons5/es/FileTray'
// import MiaoDirectory from '@/plugins/miaoDirectory/miaoDirectory.vue' // import MiaoDirectory from '@/plugins/miaoDirectory/miaoDirectory.vue'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: 'miaoDirectory', key: 'miaoDirectory',
name: '文件夹', name: '文件夹',
icon: FileTray, icon: FileTray,
getComponent: async () => getComponent: async () =>
(await import('@/plugins/miaoDirectory/miaoDirectory.vue')).default, (await import('@/plugins/miaoDirectory/miaoDirectory.vue')).default,
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vFiles.length) { if (vFiles.length) {
return false return false
} }
return vDirs.length === 1 return vDirs.length === 1
} }
} }
export default pluginConfig export default pluginConfig
import { PluginExportType } from '@/types/type' import { PluginExportType } from '@/types/type'
export const type = PluginExportType.component export const type = PluginExportType.component
+34 -31
View File
@@ -1,37 +1,40 @@
import { Plugin, PluginGroup } from "@/class/PluginCenter"; import { Plugin, PluginGroup } from '@/class/PluginCenter'
import { PluginExportType } from "@/types/type"; import { PluginExportType } from '@/types/type'
import { watch } from "vue"; import { watch } from 'vue'
const pluginConfig: Plugin = { const pluginConfig: Plugin = {
name: "初始化完成之后打开miaoDirectory", name: '初始化完成之后打开miaoDirectory',
filter: () => { filter: () => {
return false; return false
}, },
disable: false, disable: false,
group: [PluginGroup.immediately], group: [PluginGroup.immediately],
func: (_, __, hooks) => { func: (_, __, hooks) => {
const { getPluginCenter, getRootVDirectory, getViews } = hooks const { getPluginCenter, getRootVDirectory, getViews } = hooks
const views = getViews(); const views = getViews()
const pc = getPluginCenter(); const pc = getPluginCenter()
const root = getRootVDirectory(); const root = getRootVDirectory()
setTimeout(() => { setTimeout(() => {
if (views.length === 0) { if (views.length === 0) {
pc.usePlugin('miaoDirectory', [root]) pc.usePlugin('miaoDirectory', [root])
} }
watch(() => views.length, () => { watch(
if(views.length === 0) { () => views.length,
pc.usePlugin('miaoDirectory', [root]) () => {
} if (views.length === 0) {
}) pc.usePlugin('miaoDirectory', [root])
}
}
)
pc.deregister('miaoDirectory_onInit') pc.deregister('miaoDirectory_onInit')
}) })
}, },
priority: -1 priority: -1
}; }
export default pluginConfig; export default pluginConfig
export const type = PluginExportType.default; export const type = PluginExportType.default
export const key = "miaoDirectory_onInit"; export const key = 'miaoDirectory_onInit'
File diff suppressed because it is too large. Load diff
+15 -16
View File
@@ -2,25 +2,24 @@ import { registerComponentOption } from '@/class/PluginCenter'
import LogoChrome from '@vicons/ionicons5/es/LogoChrome' import LogoChrome from '@vicons/ionicons5/es/LogoChrome'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: 'miaoIframe', key: 'miaoIframe',
name: '框架', name: '框架',
icon: LogoChrome, icon: LogoChrome,
getComponent: async () => getComponent: async () =>
(await import('@/plugins/miaoIframe/miaoIframe.vue')).default, (await import('@/plugins/miaoIframe/miaoIframe.vue')).default,
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vDirs.length !== 0) { if (vDirs.length !== 0) {
return false return false
} }
if (vFiles.length !== 1) { if (vFiles.length !== 1) {
return false return false
} }
return vFiles[0].name.endsWith('html') return vFiles[0].name.endsWith('html')
}, },
priority: 2 priority: 2
} }
export default pluginConfig export default pluginConfig
import { PluginExportType } from '@/types/type' import { PluginExportType } from '@/types/type'
export const type = PluginExportType.component export const type = PluginExportType.component
+28 -26
View File
@@ -1,52 +1,54 @@
<template> <template>
<div class="miao-markdown-container-miaomiaomiao"> <div class="miao-markdown-container-miaomiaomiao">
<iframe <iframe
ref="iframeRef" ref="iframeRef"
:src="iframeSrc" :src="iframeSrc"
frameborder="0" frameborder="0"
class="iframe-container-iframe"></iframe> class="iframe-container-iframe"
</div> ></iframe>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import VirtualDirectory, { VirtualFile } from '@/class/VirtualDirectory' import VirtualDirectory, { VirtualFile } from '@/class/VirtualDirectory'
import cloneDeep from 'lodash/cloneDeep'; import cloneDeep from 'lodash/cloneDeep'
import { inject, onMounted, ref } from 'vue' import { inject, onMounted, ref } from 'vue'
import buildFromTree from '../../hooks/buildFromTree'; import buildFromTree from '../../hooks/buildFromTree'
const root = inject('rootDirectory') as VirtualDirectory const root = inject('rootDirectory') as VirtualDirectory
const currentFiles = defineModel<VirtualFile[]>('currentFiles', { const currentFiles = defineModel<VirtualFile[]>('currentFiles', {
required: true required: true
}) })
const iframeSrc = ref<string>() const iframeSrc = ref<string>()
const iframeRef = ref<HTMLIFrameElement>(); const iframeRef = ref<HTMLIFrameElement>()
const sendRootTree = () => { const sendRootTree = () => {
iframeRef.value?.contentWindow && iframeRef.value.contentWindow.postMessage(cloneDeep(root.tree), "*"); iframeRef.value?.contentWindow &&
iframeRef.value.contentWindow.postMessage(cloneDeep(root.tree), '*')
} }
const handleIframeMessage = (e: MessageEvent<any>) => { const handleIframeMessage = (e: MessageEvent<any>) => {
e e
// const data = e.data; // const data = e.data;
sendRootTree() sendRootTree()
} }
onMounted(() => { onMounted(() => {
iframeSrc.value = currentFiles.value[0].url iframeSrc.value = currentFiles.value[0].url
if (typeof window.addEventListener != "undefined") { if (typeof window.addEventListener != 'undefined') {
window.addEventListener("message", handleIframeMessage, false); window.addEventListener('message', handleIframeMessage, false)
} }
console.log(buildFromTree(cloneDeep(root.tree))) console.log(buildFromTree(cloneDeep(root.tree)))
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.miao-markdown-container-miaomiaomiao { .miao-markdown-container-miaomiaomiao {
width: 100%; width: 100%;
height: 100%; height: 100%;
.iframe-container-iframe { .iframe-container-iframe {
width: inherit; width: inherit;
height: inherit; height: inherit;
} }
} }
</style> </style>
+36 -37
View File
@@ -3,47 +3,46 @@ import VirtualDirectory, { VirtualFile } from '@/class/VirtualDirectory'
import { Image } from '@vicons/ionicons5' import { Image } from '@vicons/ionicons5'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: 'miaoImages', key: 'miaoImages',
name: '图片浏览', name: '图片浏览',
icon: Image, icon: Image,
getComponent: async () => getComponent: async () =>
(await import('@/plugins/miaoImages/miaoImages.vue')).default, (await import('@/plugins/miaoImages/miaoImages.vue')).default,
filter: (vDirs: VirtualDirectory[], vFiles: VirtualFile[]) => { filter: (vDirs: VirtualDirectory[], vFiles: VirtualFile[]) => {
if (vDirs.length === 0 && vFiles.length === 0) { if (vDirs.length === 0 && vFiles.length === 0) {
return false return false
} }
if (vDirs.length) { if (vDirs.length) {
return true return true
} }
for (let vf of vFiles) for (let vf of vFiles)
for (let end of [ for (let end of [
'xbm', 'xbm',
'tif', 'tif',
'pjp', 'pjp',
'svgz', 'svgz',
'jpg', 'jpg',
'jpeg', 'jpeg',
'ico', 'ico',
'tiff', 'tiff',
'gif', 'gif',
'svg', 'svg',
'jfif', 'jfif',
'webp', 'webp',
'png', 'png',
'.bmp', '.bmp',
'pjpeg', 'pjpeg',
'avif' 'avif'
]) { ]) {
if (vf.name.endsWith(end)) { if (vf.name.endsWith(end)) {
return true return true
}
} }
return false }
} return false
}
} }
export default pluginConfig export default pluginConfig
import { PluginExportType } from '@/types/type' import { PluginExportType } from '@/types/type'
export const type = PluginExportType.component export const type = PluginExportType.component
+293 -284
View File
@@ -1,62 +1,76 @@
<template> <template>
<miao-drop-handler <miao-drop-handler
@on-virtual-directory="handleDrop" @on-virtual-directory="handleDrop"
@on-virtual-files="handleDrop"> @on-virtual-files="handleDrop"
<miao-message-provider ref="miaoMessageRef"> >
<div class="miaoImage" ref="rootRef"> <miao-message-provider ref="miaoMessageRef">
<n-scrollbar ref="NScrollbarRef" style="max-height: 100%;"> <div
<div class="miaoImage"
class="miaoImage-container" ref="rootRef"
v-for="imageGroup in imageGroupList"> >
<div class="miaoImage-container-day"> <n-scrollbar
<!-- <div class="miaoImage-container-divide miaoImage-container-divide-before"> ref="NScrollbarRef"
style="max-height: 100%"
>
<div
class="miaoImage-container"
v-for="imageGroup in imageGroupList"
>
<div class="miaoImage-container-day">
<!-- <div class="miaoImage-container-divide miaoImage-container-divide-before">
<div class="miaoImage-container-divide-line"></div> <div class="miaoImage-container-divide-line"></div>
</div> --> </div> -->
<span class="miaoImage-container-day-text"> <span class="miaoImage-container-day-text">
{{ imageGroup.day }} {{ imageGroup.day }}
</span> </span>
<!-- <div class="miaoImage-container-divide"> <!-- <div class="miaoImage-container-divide">
<div class="miaoImage-container-divide-line"></div> <div class="miaoImage-container-divide-line"></div>
</div> --> </div> -->
</div> </div>
<div <div
class="miaoImage-container-row" class="miaoImage-container-row"
v-for="vFile in imageGroup.items" v-for="vFile in imageGroup.items"
:key="vFile.id"> :key="vFile.id"
<img >
:src="vFile.url" <img
class="miaoImage-container-row-image" :src="vFile.url"
loading="lazy" class="miaoImage-container-row-image"
:class=" loading="lazy"
activeImage === vFile :class="
? 'miaoImage-container-row-image-active' activeImage === vFile
: '' ? 'miaoImage-container-row-image-active'
" : ''
@click="activeImage = vFile" /> "
</div> @click="activeImage = vFile"
</div> />
</n-scrollbar> </div>
<miao-mask </div>
:show="activeImage !== undefined" </n-scrollbar>
@click="activeImage = undefined" <miao-mask
class="miaoImage-mask" :show="activeImage !== undefined"
@wheel="handleWheel"> @click="activeImage = undefined"
<ChevronBack class="miaoImage-mask"
class="miaoImage-mask-btn miaoImage-mask-btn-back" @wheel="handleWheel"
@click="handleActiveImageBack" /> >
<img <ChevronBack
:src="activeImage?.url" class="miaoImage-mask-btn miaoImage-mask-btn-back"
class="miaoImage-mask-active" @click="handleActiveImageBack"
@click="(e) => e.stopPropagation()" />
draggable="false" <img
:style="{transform: `scale(${imgViewScale})`}" /> :src="activeImage?.url"
<ChevronForward class="miaoImage-mask-active"
class="miaoImage-mask-btn miaoImage-mask-btn-forward" @click="(e) => e.stopPropagation()"
@click="handleActiveImageForward" /> draggable="false"
</miao-mask> :style="{ transform: `scale(${imgViewScale})` }"
</div> />
</miao-message-provider> <ChevronForward
</miao-drop-handler> class="miaoImage-mask-btn miaoImage-mask-btn-forward"
@click="handleActiveImageForward"
/>
</miao-mask>
</div>
</miao-message-provider>
</miao-drop-handler>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -70,32 +84,32 @@ import { NScrollbar } from 'naive-ui'
import { ChevronBack, ChevronForward } from '@vicons/ionicons5' import { ChevronBack, ChevronForward } from '@vicons/ionicons5'
const imageSuffixList = [ const imageSuffixList = [
'xbm', 'xbm',
'tif', 'tif',
'pjp', 'pjp',
'svgz', 'svgz',
'jpg', 'jpg',
'jpeg', 'jpeg',
'ico', 'ico',
'tiff', 'tiff',
'gif', 'gif',
'svg', 'svg',
'jfif', 'jfif',
'webp', 'webp',
'png', 'png',
'bmp', 'bmp',
'pjpeg', 'pjpeg',
'avif' 'avif'
] ]
const currentDirectories = defineModel<VirtualDirectory[]>( const currentDirectories = defineModel<VirtualDirectory[]>(
'currentDirectories', 'currentDirectories',
{ {
required: true required: true
} }
) )
const currentFiles = defineModel<VirtualFile[]>('currentFiles', { const currentFiles = defineModel<VirtualFile[]>('currentFiles', {
required: true required: true
}) })
const NScrollbarRef = ref() const NScrollbarRef = ref()
@@ -106,263 +120,258 @@ const imageFileList = ref<VirtualFile[]>([])
const activeImage = ref<VirtualFile>() const activeImage = ref<VirtualFile>()
const imageGroupList = computed(() => { const imageGroupList = computed(() => {
return groupByDay(imageFileList.value) return groupByDay(imageFileList.value)
}) })
watch(activeImage, () => { watch(activeImage, () => {
nextTick(scrollToActiveImage) nextTick(scrollToActiveImage)
imgViewScale.value = 1 imgViewScale.value = 1
}) })
const groupByDay = (array: VirtualFile[]) => { const groupByDay = (array: VirtualFile[]) => {
const result = [] const result = []
let currentDay = null let currentDay = null
let currentGroup: VirtualFile[] = [] let currentGroup: VirtualFile[] = []
for (const item of array) { for (const item of array) {
const date = new Date(item.stats.mtimeMs) const date = new Date(item.stats.mtimeMs)
const day = `${date.getFullYear()}年 ${String( const day = `${date.getFullYear()}年 ${String(
date.getMonth() + 1 date.getMonth() + 1
).padStart(2, '0')}月 ${String(date.getDate()).padStart(2, '0')}日` ).padStart(2, '0')}月 ${String(date.getDate()).padStart(2, '0')}日`
if (day !== currentDay) { if (day !== currentDay) {
if (currentGroup.length > 0) { if (currentGroup.length > 0) {
result.push({ result.push({
day: currentDay, day: currentDay,
items: currentGroup items: currentGroup
}) })
} }
currentDay = day currentDay = day
currentGroup = [item] currentGroup = [item]
} else { } else {
currentGroup.push(item) currentGroup.push(item)
} }
} }
if (currentGroup.length > 0) { if (currentGroup.length > 0) {
result.push({ result.push({
day: currentDay, day: currentDay,
items: currentGroup items: currentGroup
}) })
} }
return result return result
} }
const scrollToActiveImage = () => { const scrollToActiveImage = () => {
const dom = rootRef.value?.querySelector( const dom = rootRef.value?.querySelector(
'.miaoImage-container-row-image-active' '.miaoImage-container-row-image-active'
) )
dom && NScrollbarRef.value.scrollTo({ dom &&
top: dom.offsetTop - 30, NScrollbarRef.value.scrollTo({
behavior: 'smooth' top: dom.offsetTop - 30,
}) behavior: 'smooth'
})
} }
const handleActiveImageBack = (e: any) => { const handleActiveImageBack = (e: any) => {
e.stopPropagation() e.stopPropagation()
if (!activeImage.value) { if (!activeImage.value) {
return return
} }
const index = imageFileList.value.indexOf(activeImage.value) const index = imageFileList.value.indexOf(activeImage.value)
activeImage.value = activeImage.value =
imageFileList.value[ imageFileList.value[
(index - 1 + imageFileList.value.length) % (index - 1 + imageFileList.value.length) % imageFileList.value.length
imageFileList.value.length ]
]
} }
const handleActiveImageForward = (e: any) => { const handleActiveImageForward = (e: any) => {
e.stopPropagation() e.stopPropagation()
if (!activeImage.value) { if (!activeImage.value) {
return return
} }
const index = imageFileList.value.indexOf(activeImage.value) const index = imageFileList.value.indexOf(activeImage.value)
activeImage.value = activeImage.value =
imageFileList.value[ imageFileList.value[
(index + 1 + imageFileList.value.length) % (index + 1 + imageFileList.value.length) % imageFileList.value.length
imageFileList.value.length ]
]
} }
const handleDrop = async (vItems: (VirtualFile | VirtualDirectory)[]) => { const handleDrop = async (vItems: (VirtualFile | VirtualDirectory)[]) => {
const length_before = imageFileList.value.length const length_before = imageFileList.value.length
if (vItems[0].type === 'directory') { if (vItems[0].type === 'directory') {
// @ts-ignore // @ts-ignore
currentDirectories.value = [...currentDirectories.value, ...vItems] currentDirectories.value = [...currentDirectories.value, ...vItems]
for (const i of vItems) { for (const i of vItems) {
// @ts-ignore // @ts-ignore
await updateImageSrcList(i) await updateImageSrcList(i)
} }
} else { } else {
// @ts-ignore // @ts-ignore
currentFiles.value = [...currentFiles, ...vItems] currentFiles.value = [...currentFiles, ...vItems]
// @ts-ignore // @ts-ignore
await updateImageSrcList(vItems) await updateImageSrcList(vItems)
} }
miaoMessageRef.value?.alertTip( miaoMessageRef.value?.alertTip(
length_before === imageFileList.value.length length_before === imageFileList.value.length
? '未发现任何可添加图片' ? '未发现任何可添加图片'
: `导入${imageFileList.value.length - length_before}张图片`, : `导入${imageFileList.value.length - length_before}张图片`,
{ {
type: type:
length_before === imageFileList.value.length length_before === imageFileList.value.length ? 'info' : 'success',
? 'info' timeout: 5000
: 'success', }
timeout: 5000 )
}
)
} }
const updateImageSrcList = async (source: VirtualFile[] | VirtualDirectory) => { const updateImageSrcList = async (source: VirtualFile[] | VirtualDirectory) => {
let newFileList: VirtualFile[] let newFileList: VirtualFile[]
if ('type' in source) { if ('type' in source) {
await source.update() await source.update()
newFileList = [ newFileList = [
...(source.files?.filter((v) => ...(source.files?.filter((v) =>
imageSuffixList.includes(v.name.split('.').pop() ?? '') imageSuffixList.includes(v.name.split('.').pop() ?? '')
) ?? []) ) ?? [])
] ]
} else { } else {
newFileList = [ newFileList = [
...(source.filter((v) => ...(source.filter((v) =>
imageSuffixList.includes(v.name.split('.').pop() ?? '') imageSuffixList.includes(v.name.split('.').pop() ?? '')
) ?? []) ) ?? [])
] ]
} }
imageFileList.value = uniq([...imageFileList.value, ...newFileList]).sort( imageFileList.value = uniq([...imageFileList.value, ...newFileList]).sort(
(a, b) => -a.stats.mtimeMs + b.stats.mtimeMs (a, b) => -a.stats.mtimeMs + b.stats.mtimeMs
) )
} }
const handleWheel = (e: WheelEvent) => { const handleWheel = (e: WheelEvent) => {
if (e.deltaY < 0) { if (e.deltaY < 0) {
imgViewScale.value *= 1.42857 imgViewScale.value *= 1.42857
} else { } else {
imgViewScale.value /= 1.42857 imgViewScale.value /= 1.42857
} }
} }
onMounted(async () => { onMounted(async () => {
const length_before = imageFileList.value.length const length_before = imageFileList.value.length
for (const i of [currentFiles.value, ...currentDirectories.value]) { for (const i of [currentFiles.value, ...currentDirectories.value]) {
await updateImageSrcList(i) await updateImageSrcList(i)
} }
miaoMessageRef.value?.alertTip( miaoMessageRef.value?.alertTip(
length_before === imageFileList.value.length length_before === imageFileList.value.length
? '未发现任何新增图片' ? '未发现任何新增图片'
: `导入${imageFileList.value.length - length_before}张图片`, : `导入${imageFileList.value.length - length_before}张图片`,
{ {
type: type:
length_before === imageFileList.value.length length_before === imageFileList.value.length ? 'info' : 'success',
? 'info' timeout: 5000
: 'success', }
timeout: 5000 )
}
)
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.miaoImage { .miaoImage {
width: 100%; width: 100%;
height: 100%; height: 100%;
position: relative; position: relative;
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 10px; gap: 10px;
.miaoImage-container { .miaoImage-container {
width: 100%; width: 100%;
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
margin-bottom: 20px; margin-bottom: 20px;
margin-top: 20px; margin-top: 20px;
.miaoImage-container-day { .miaoImage-container-day {
width: 100%; width: 100%;
display: flex; display: flex;
align-items: center; align-items: center;
position: relative;
margin: 0 20px;
.miaoImage-container-divide {
flex: 1;
height: 100%;
position: relative; position: relative;
margin: 0 20px;
.miaoImage-container-divide {
flex: 1;
height: 100%;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.miaoImage-container-divide-line {
height: 3px;
width: 100%;
border-radius: 5px;
background-color: rgb(244 244 244);
}
.miaoImage-container-divide-before {
flex: 0.1;
}
.miaoImage-container-day-text {
margin: 0 0 0 10px;
font-size: 15px;
user-select: none;
}
}
.miaoImage-container-row {
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
width: 25%; }
.miaoImage-container-divide-line {
height: 3px;
width: 100%;
border-radius: 5px;
background-color: rgb(244 244 244);
}
.miaoImage-container-divide-before {
flex: 0.1;
}
.miaoImage-container-day-text {
margin: 0 0 0 10px;
font-size: 15px;
user-select: none;
}
}
.miaoImage-container-row {
display: flex;
justify-content: center;
align-items: center;
width: 25%;
aspect-ratio: 1;
.miaoImage-container-row-image {
width: 80%;
aspect-ratio: 1; aspect-ratio: 1;
object-fit: cover;
transition: width 0.25s;
box-shadow: 0 0 10px -5px;
cursor: pointer;
user-select: none;
.miaoImage-container-row-image { &:hover {
width: 80%; width: 90%;
aspect-ratio: 1;
object-fit: cover;
transition: width 0.25s;
box-shadow: 0 0 10px -5px;
cursor: pointer;
user-select: none;
&:hover {
width: 90%;
}
&-active {
width: 90%;
}
} }
}
}
.miaoImage-mask { &-active {
background-color: rgba(0, 0, 0, 0.444); width: 90%;
overflow: hidden; }
} }
}
}
.miaoImage-mask-active { .miaoImage-mask {
max-width: 80%; background-color: rgba(0, 0, 0, 0.444);
max-height: 80%; overflow: hidden;
user-select: none; }
}
.miaoImage-mask-btn { .miaoImage-mask-active {
color: #ffffff99; max-width: 80%;
width: 7%; max-height: 80%;
position: absolute; user-select: none;
cursor: pointer; }
&-back { .miaoImage-mask-btn {
left: 1%; color: #ffffff99;
} width: 7%;
position: absolute;
cursor: pointer;
&-forward { &-back {
right: 1%; left: 1%;
} }
}
&-forward {
right: 1%;
}
}
} }
</style> </style>
+14 -15
View File
@@ -2,24 +2,23 @@ import { registerComponentOption } from '@/class/PluginCenter'
import DocumentText from '@vicons/ionicons5/es/DocumentText' import DocumentText from '@vicons/ionicons5/es/DocumentText'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: 'miaoMarkdown', key: 'miaoMarkdown',
name: 'markdown浏览', name: 'markdown浏览',
icon: DocumentText, icon: DocumentText,
getComponent: async () => getComponent: async () =>
(await import('@/plugins/miaoMarkdown/miaoMarkdown.vue')).default, (await import('@/plugins/miaoMarkdown/miaoMarkdown.vue')).default,
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vDirs.length !== 0) { if (vDirs.length !== 0) {
return false return false
} }
if (vFiles.length !== 1) { if (vFiles.length !== 1) {
return false return false
} }
return vFiles[0].name.endsWith('md') return vFiles[0].name.endsWith('md')
} }
} }
export default pluginConfig export default pluginConfig
import { PluginExportType } from '@/types/type' import { PluginExportType } from '@/types/type'
export const type = PluginExportType.component export const type = PluginExportType.component
+39 -35
View File
@@ -1,24 +1,26 @@
<template> <template>
<n-scrollbar> <n-scrollbar>
<div class="miao-markdown-container-miaomiaomiao" v-html="renderedMarkdown"></div> <div
<div style="height: 50px; width: 100%;"></div> class="miao-markdown-container-miaomiaomiao"
</n-scrollbar> v-html="renderedMarkdown"
></div>
<div style="height: 50px; width: 100%"></div>
</n-scrollbar>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { NScrollbar } from 'naive-ui'; import { NScrollbar } from 'naive-ui'
import { VirtualFile } from '@/class/VirtualDirectory' import { VirtualFile } from '@/class/VirtualDirectory'
import { onMounted, ref } from 'vue' import { onMounted, ref } from 'vue'
import MarkdownIt from 'markdown-it' import MarkdownIt from 'markdown-it'
import useMiaoFetchApi from '@/hooks/useMiaoFetchApi'; import useMiaoFetchApi from '@/hooks/useMiaoFetchApi'
const decoder = new TextDecoder('utf-8')
const decoder = new TextDecoder('utf-8');
const miaoFetchApi = useMiaoFetchApi() const miaoFetchApi = useMiaoFetchApi()
const currentFiles = defineModel<VirtualFile[]>('currentFiles', { const currentFiles = defineModel<VirtualFile[]>('currentFiles', {
required: true required: true
}) })
const markdownSrc = ref<string>() const markdownSrc = ref<string>()
@@ -27,41 +29,43 @@ const renderedMarkdown = ref<string>('')
const md = new MarkdownIt() const md = new MarkdownIt()
onMounted(async () => { onMounted(async () => {
markdownSrc.value = currentFiles.value[0].url markdownSrc.value = currentFiles.value[0].url
const text = decoder.decode(await(miaoFetchApi.getFile(currentFiles.value[0])).response) const text = decoder.decode(
renderedMarkdown.value = md.render(text) await miaoFetchApi.getFile(currentFiles.value[0]).response
)
renderedMarkdown.value = md.render(text)
}) })
</script> </script>
<style lang="scss"> <style lang="scss">
.miao-markdown-container-miaomiaomiao { .miao-markdown-container-miaomiaomiao {
width: 95%; width: 95%;
margin: 20px; margin: 20px;
table, table,
td, td,
th { th {
border: 1px solid #ddd; border: 1px solid #ddd;
text-align: left; text-align: left;
} }
table { table {
border-collapse: collapse; border-collapse: collapse;
margin-bottom: 20px; margin-bottom: 20px;
} }
th, th,
td { td {
padding: 15px; padding: 15px;
} }
tr:nth-child(even) { tr:nth-child(even) {
background-color: #f2f2f2 background-color: #f2f2f2;
} }
th { th {
background-color: #04AA6D; background-color: #04aa6d;
color: white; color: white;
} }
} }
</style> </style>
+32 -32
View File
@@ -1,36 +1,36 @@
import { registerComponentOption } from "@/class/PluginCenter"; import { registerComponentOption } from '@/class/PluginCenter'
import { PluginExportType } from "@/types/type"; import { PluginExportType } from '@/types/type'
import Disc from "@vicons/ionicons5/es/Disc"; import Disc from '@vicons/ionicons5/es/Disc'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: "miaoMusicPlayer", key: 'miaoMusicPlayer',
name: "音乐", name: '音乐',
icon: Disc, icon: Disc,
getComponent: async () => (await import("./miaoMusicPlayer.vue")).default, getComponent: async () => (await import('./miaoMusicPlayer.vue')).default,
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vDirs.length === 0 && vFiles.length === 0) { if (vDirs.length === 0 && vFiles.length === 0) {
return true; return true
} }
if (vDirs.length !== 0) { if (vDirs.length !== 0) {
return false; return false
} }
if (vFiles.length === 0) { if (vFiles.length === 0) {
return false; return false
} }
for (let i of vFiles) { for (let i of vFiles) {
for (let s of ["mp3", "flac", "ogg", "mp4"]) { for (let s of ['mp3', 'flac', 'ogg', 'mp4']) {
if (i.name.endsWith(s)) { if (i.name.endsWith(s)) {
return true; return true
} }
} }
} }
return false; return false
}, },
disable: false, disable: false,
single: true, single: true,
priority: 5 priority: 5
}; }
export default pluginConfig; export default pluginConfig
export const type = PluginExportType.component; export const type = PluginExportType.component
+21 -21
View File
@@ -1,26 +1,26 @@
import { Plugin, PluginGroup } from "@/class/PluginCenter"; import { Plugin, PluginGroup } from '@/class/PluginCenter'
import { PluginExportType } from "@/types/type"; import { PluginExportType } from '@/types/type'
import { shallowRef } from "vue"; import { shallowRef } from 'vue'
import Disc from "@vicons/ionicons5/es/Disc"; import Disc from '@vicons/ionicons5/es/Disc'
const pluginConfig: Plugin = { const pluginConfig: Plugin = {
name: "音乐", name: '音乐',
icon: shallowRef(Disc), icon: shallowRef(Disc),
filter: (_, __, views) => { filter: (_, __, views) => {
return views.find("miaoMusicPlayer").length === 0; return views.find('miaoMusicPlayer').length === 0
}, },
disable: false, disable: false,
group: [PluginGroup.mainMenu], group: [PluginGroup.mainMenu],
func(_, __, hooks) { func(_, __, hooks) {
const { getPluginCenter } = hooks; const { getPluginCenter } = hooks
const PluginCenter = getPluginCenter(); const PluginCenter = getPluginCenter()
PluginCenter.usePlugin("miaoMusicPlayer", [], []); PluginCenter.usePlugin('miaoMusicPlayer', [], [])
}, },
priority: -1 priority: -1
}; }
export default pluginConfig; export default pluginConfig
export const type = PluginExportType.default; export const type = PluginExportType.default
export const key = "musicPlayer-mainMenu"; export const key = 'musicPlayer-mainMenu'
@@ -1,49 +1,51 @@
import { createApp, Reactive } from "vue"; import { createApp, Reactive } from 'vue'
import aplayerListNew from "../src/components/aplayerListNew.vue"; import aplayerListNew from '../src/components/aplayerListNew.vue'
import apType, { audioType } from "../types/ap"; import apType, { audioType } from '../types/ap'
export type aplayerMiaoOption = { export type aplayerMiaoOption = {
onDragItemStart?: () => void onDragItemStart?: () => void
onDragItemEnd?: () => void onDragItemEnd?: () => void
onPlayVideo?: (element: audioType) => void onPlayVideo?: (element: audioType) => void
onSaveCollection?: (audios: audioType[]) => void onSaveCollection?: (audios: audioType[]) => void
} }
/** /**
* 对aplayer进行一些自定义的风格优化 * 对aplayer进行一些自定义的风格优化
*/ */
const useAplayerMiao = (ap: Reactive<apType>, options?: aplayerMiaoOption) => { const useAplayerMiao = (ap: Reactive<apType>, options?: aplayerMiaoOption) => {
const container = ap.container as HTMLDivElement; const container = ap.container as HTMLDivElement
// 隐藏旧版歌单 // 隐藏旧版歌单
const old_listDom = container.querySelector(".aplayer-list") as HTMLDivElement; const old_listDom = container.querySelector(
old_listDom.style.display = "none"; '.aplayer-list'
) as HTMLDivElement
old_listDom.style.display = 'none'
// 新版歌单 // 新版歌单
const new_list_dom = document.createElement("div"); const new_list_dom = document.createElement('div')
new_list_dom.classList.add("aplayer-list"); new_list_dom.classList.add('aplayer-list')
new_list_dom.style.maxHeight = ap.options.listMaxHeight; new_list_dom.style.maxHeight = ap.options.listMaxHeight
ap.on("listadd", () => { ap.on('listadd', () => {
ap.list.audios.forEach(v => { ap.list.audios.forEach((v) => {
!v.id && (v.id = Math.random()); !v.id && (v.id = Math.random())
}); })
}); })
ap.on("listshow", () => { ap.on('listshow', () => {
new_list_dom.classList.remove("aplayer-list-hide"); new_list_dom.classList.remove('aplayer-list-hide')
}); })
ap.on("listhide", () => { ap.on('listhide', () => {
new_list_dom.classList.add("aplayer-list-hide"); new_list_dom.classList.add('aplayer-list-hide')
}); })
container.appendChild(new_list_dom); container.appendChild(new_list_dom)
const app = createApp(aplayerListNew, { ap, ...(options ?? {}) }); const app = createApp(aplayerListNew, { ap, ...(options ?? {}) })
app.mount(new_list_dom); app.mount(new_list_dom)
ap.on("destroy", () => { ap.on('destroy', () => {
app.unmount(); app.unmount()
}); })
return app; return app
}; }
export default useAplayerMiao; export default useAplayerMiao
+167 -139
View File
@@ -1,29 +1,44 @@
<template> <template>
<miao-drop-handler @on-virtual-files="handleDropVFiles"> <miao-drop-handler @on-virtual-files="handleDropVFiles">
<miao-alert-tip-provider ref="miaoMessageRef"> <miao-alert-tip-provider ref="miaoMessageRef">
<div class="miaoMusic-container"> <div class="miaoMusic-container">
<miao-music-main v-if="ap" :ap="ap" v-model:data="data" :updateLocalData="updateLocalData" <miao-music-main
@new-collection="saveCurrPlayList"></miao-music-main> v-if="ap"
<miao-mask :show="isAPlayerListShow" style="z-index: 5" @click="() => ap?.list.hide()"></miao-mask> :ap="ap"
<div ref="aplayer" style="z-index: 10" /> v-model:data="data"
<miao-mask :show="isSavingCollection" @click="isSavingCollection = false"></miao-mask> :updateLocalData="updateLocalData"
</div> @new-collection="saveCurrPlayList"
</miao-alert-tip-provider> ></miao-music-main>
</miao-drop-handler> <miao-mask
:show="isAPlayerListShow"
style="z-index: 5"
@click="() => ap?.list.hide()"
></miao-mask>
<div
ref="aplayer"
style="z-index: 10"
/>
<miao-mask
:show="isSavingCollection"
@click="isSavingCollection = false"
></miao-mask>
</div>
</miao-alert-tip-provider>
</miao-drop-handler>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import useAplayerMiao from './hooks/aplayerMiao' import useAplayerMiao from './hooks/aplayerMiao'
import { VirtualFile } from '@/class/VirtualDirectory' import { VirtualFile } from '@/class/VirtualDirectory'
import { import {
App, App,
onBeforeMount, onBeforeMount,
onMounted, onMounted,
onUnmounted, onUnmounted,
reactive, reactive,
ref, ref,
toRaw, toRaw,
watch watch
} from 'vue' } from 'vue'
import './src/APlayer.fix.css' import './src/APlayer.fix.css'
// @ts-ignore // @ts-ignore
@@ -53,167 +68,180 @@ const isAPlayerListShow = ref(true)
const isSavingCollection = ref(false) const isSavingCollection = ref(false)
const currentFiles = defineModel<VirtualFile[]>('currentFiles', { const currentFiles = defineModel<VirtualFile[]>('currentFiles', {
required: true required: true
}) })
const props = defineProps<{ const props = defineProps<{
view: VirtualPage view: VirtualPage
}>() }>()
const data = ref<collectionType[]>() const data = ref<collectionType[]>()
watch( watch(
data, data,
(_v, oldV) => { (_v, oldV) => {
updateLocalData(oldV !== undefined) updateLocalData(oldV !== undefined)
}, },
{ {
deep: true deep: true
} }
) )
watch( watch(
() => currentFiles.value, () => currentFiles.value,
(value, oldValue) => { (value, oldValue) => {
const diff = difference(value, oldValue) const diff = difference(value, oldValue)
if (diff.length > 0) { if (diff.length > 0) {
const _s = `等${diff.length}个资源` const _s = `等${diff.length}个资源`
miaoMessageRef.value?.alertTip( miaoMessageRef.value?.alertTip(
`已添加 ${diff[0].name}${diff.length !== 1 ? _s : ''}`, `已添加 ${diff[0].name}${diff.length !== 1 ? _s : ''}`,
{ {
type: 'success', type: 'success',
timeout: 3000 timeout: 3000
} }
) )
ap?.value?.list.add(getMusicList(diff)) ap?.value?.list.add(getMusicList(diff))
} }
} }
) )
const getMusicList = (mp3VFiles: VirtualFile[]) => const getMusicList = (mp3VFiles: VirtualFile[]) =>
mp3VFiles.map((v, index) => ({ mp3VFiles.map((v, index) => ({
url: `${config.baseUrl}${v.url}`, url: `${config.baseUrl}${v.url}`,
name: v.name, name: v.name,
artist: ' ', artist: ' ',
index index
})) }))
const handleDropVFiles = (files: VirtualFile[]) => { const handleDropVFiles = (files: VirtualFile[]) => {
currentFiles.value = uniq([...currentFiles.value, ...files]) currentFiles.value = uniq([...currentFiles.value, ...files])
} }
const saveCurrPlayList = () => { const saveCurrPlayList = () => {
if (ap.value) { if (ap.value) {
data.value?.unshift({ data.value?.unshift({
id: Math.random(), id: Math.random(),
name: `新建歌单-${new Date()}`, name: `新建歌单-${new Date()}`,
intro: 'none', intro: 'none',
createTime: new Date(), createTime: new Date(),
coverUrl: '', coverUrl: '',
audios: cloneDeep(ap.value.list.audios).map((v, i) => ({ ...v, index: i })) audios: cloneDeep(ap.value.list.audios).map((v, i) => ({
}) ...v,
miaoMessageRef.value?.alertTip('已创建新的歌单', { index: i
timeout: 1000, }))
type: 'success' })
}) miaoMessageRef.value?.alertTip('已创建新的歌单', {
} timeout: 1000,
type: 'success'
})
}
} }
const initAPlayerMiao = () => { const initAPlayerMiao = () => {
const aplayerOption = { const aplayerOption = {
container: aplayer.value, container: aplayer.value,
audio: getMusicList(currentFiles.value), audio: getMusicList(currentFiles.value),
autoplay: true, autoplay: true,
volume: 1, volume: 1,
theme: '#60e8a2', theme: '#60e8a2',
listMaxHeight: '500px' listMaxHeight: '500px'
} }
ap.value = reactive<apType>(new APlayer(aplayerOption)) ap.value = reactive<apType>(new APlayer(aplayerOption))
vueApp = useAplayerMiao(ap.value, { vueApp = useAplayerMiao(ap.value, {
onDragItemStart: () => { }, onDragItemStart: () => {},
onDragItemEnd: () => { }, onDragItemEnd: () => {},
onPlayVideo: (element) => { onPlayVideo: (element) => {
pluginCenter.usePlugin( pluginCenter.usePlugin(
'miaoVideoPlayer', 'miaoVideoPlayer',
[], [],
[ [
currentFiles.value.find( currentFiles.value.find(
(v) => v.name === element.name (v) => v.name === element.name
) as VirtualFile ) as VirtualFile
] ]
) )
}, },
onSaveCollection: saveCurrPlayList onSaveCollection: saveCurrPlayList
}) })
ap.value.on('listremove', (...args: any) => { ap.value.on('listremove', (...args: any) => {
const { index } = args[0] as { index: number } const { index } = args[0] as { index: number }
const _name = ap?.value?.list.audios[index].name const _name = ap?.value?.list.audios[index].name
currentFiles.value = currentFiles.value.filter((v) => v.name !== _name) currentFiles.value = currentFiles.value.filter((v) => v.name !== _name)
}) })
ap.value.on('play', () => { ap.value.on('play', () => {
const name = ap.value?.list.audios[ap.value.list.index].name as string const name = ap.value?.list.audios[ap.value.list.index].name as string
props.view.setTitle(name) props.view.setTitle(name)
}) })
ap.value.on('listshow', () => { ap.value.on('listshow', () => {
isAPlayerListShow.value = true isAPlayerListShow.value = true
}) })
ap.value.on('listhide', () => { ap.value.on('listhide', () => {
isAPlayerListShow.value = false isAPlayerListShow.value = false
}) })
} }
const updateLocalData = debounce((log?: boolean) => { const updateLocalData = debounce(
log && miaoMessageRef.value?.alertTip(`保存设置成功`, { (log?: boolean) => {
type: 'success', log &&
timeout: 999, miaoMessageRef.value?.alertTip(`保存设置成功`, {
}) type: 'success',
localForage.setItem('miaoMusic-storage-musicCollections', toRaw(data.value)) timeout: 999
}, 1000, { })
'leading': false, localForage.setItem(
'trailing': true 'miaoMusic-storage-musicCollections',
}) toRaw(data.value)
)
},
1000,
{
leading: false,
trailing: true
}
)
const getLocalData = async () => { const getLocalData = async () => {
const _data = const _data =
(await localForage.getItem('miaoMusic-storage-musicCollections') as collectionType[]) ?? [] ((await localForage.getItem(
_data.forEach(v => v.audios.sort((a, b) => a.index - b.index)) 'miaoMusic-storage-musicCollections'
data.value = _data )) as collectionType[]) ?? []
console.log('data ==>', toRaw(data.value)) _data.forEach((v) => v.audios.sort((a, b) => a.index - b.index))
data.value = _data
console.log('data ==>', toRaw(data.value))
} }
onBeforeMount(async () => { onBeforeMount(async () => {
await getLocalData() await getLocalData()
}) })
onMounted(async () => { onMounted(async () => {
currentFiles.value = [...currentFiles.value.reverse()] currentFiles.value = [...currentFiles.value.reverse()]
initAPlayerMiao() initAPlayerMiao()
}) })
onUnmounted(() => { onUnmounted(() => {
vueApp.unmount() vueApp.unmount()
ap?.value?.destroy() ap?.value?.destroy()
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.miaoMusic-container { .miaoMusic-container {
position: relative; position: relative;
width: 100%; width: 100%;
height: 100%; height: 100%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
background-color: #ffffff; background-color: #ffffff;
} }
</style> </style>
<style lang="scss"> <style lang="scss">
.aplayer { .aplayer {
display: flex; display: flex;
flex-direction: column-reverse; flex-direction: column-reverse;
position: absolute; position: absolute;
bottom: 10px; bottom: 10px;
width: -webkit-fill-available; width: -webkit-fill-available;
.aplayer-icon-order, .aplayer-icon-order,
.aplayer-icon-loop { .aplayer-icon-loop {
display: none !important; display: none !important;
} }
} }
</style> </style>
File diff suppressed because it is too large. Load diff
+278 -237
View File
@@ -1,101 +1,139 @@
<template> <template>
<div class="collection-info-container"> <div class="collection-info-container">
<div class="collection-info-container-top"> <div class="collection-info-container-top">
<div class="collection-info-container-top-exit" @click="emit('exit')"> <div
<ArrowBackOutline></ArrowBackOutline> class="collection-info-container-top-exit"
</div> @click="emit('exit')"
<div class="collection-info-container-top-title"> >
<span :tooltip="false" v-if="!isEditing"> <ArrowBackOutline></ArrowBackOutline>
{{ collection.name }} </div>
</span> <div class="collection-info-container-top-title">
<n-input v-if="isEditing" v-model:value="collection.name"></n-input> <span
</div> :tooltip="false"
v-if="!isEditing"
>
{{ collection.name }}
</span>
<n-input
v-if="isEditing"
v-model:value="collection.name"
></n-input>
</div>
<div class="collection-info-container-top-delete" v-if="isEditing" @click=" <div
clickDeleteCount !== 2 class="collection-info-container-top-delete"
? clickDeleteCount++ v-if="isEditing"
: emit('deleteSelf') @click="
"> clickDeleteCount !== 2 ? clickDeleteCount++ : emit('deleteSelf')
<TrashOutline></TrashOutline> "
<span> >
{{ <TrashOutline></TrashOutline>
clickDeleteCount === 0 <span>
? `删除` {{
: clickDeleteCount === 1 clickDeleteCount === 0
? '确认删除' ? `删除`
: '再次确认' : clickDeleteCount === 1
}} ? '确认删除'
</span> : '再次确认'
}}
</span>
</div>
</div>
<div class="collection-info-container-controller">
<div
class="collection-info-container-controller-play"
@click="emit('playAll', collection)"
>
<div class="collection-info-container-controller-play-icon">
<CaretForwardOutline></CaretForwardOutline>
</div> </div>
</div> <div class="collection-info-container-controller-play-text">
<div class="collection-info-container-controller"> {{ `全部播放` }}
<div class="collection-info-container-controller-play" @click="emit('playAll', collection)">
<div class="collection-info-container-controller-play-icon">
<CaretForwardOutline></CaretForwardOutline>
</div>
<div class="collection-info-container-controller-play-text">
{{ `全部播放` }}
</div>
</div> </div>
<div class="collection-info-container-controller-right"> </div>
<div class="collection-info-container-controller-edit" @click="isEditing = !isEditing"> <div class="collection-info-container-controller-right">
<component :is="isEditing ? CheckmarkOutline : CreateOutline <div
"></component> class="collection-info-container-controller-edit"
</div> @click="isEditing = !isEditing"
>
<component
:is="isEditing ? CheckmarkOutline : CreateOutline"
></component>
</div> </div>
</div> </div>
<NScrollbar> </div>
<div class="collection-info-container-audioList"> <NScrollbar>
<VueDraggable v-model="collection.audios" :animation="150" <div class="collection-info-container-audioList">
handle=".collection-info-container-audioList-item-controller-item-drag" ghostClass="iSDragging" <VueDraggable
@end="updateAudiosIndex"> v-model="collection.audios"
<div v-for="(audio, index) in collection.audios" class="collection-info-container-audioList-item"> :animation="150"
<div class="collection-info-container-audioList-item-index"> handle=".collection-info-container-audioList-item-controller-item-drag"
<div>{{ index + 1 }}</div> ghostClass="iSDragging"
</div> @end="updateAudiosIndex"
<div class="collection-info-container-audioList-item-info"> >
<div v-if="!isEditing" class="collection-info-container-audioList-item-info-name"> <div
<NEllipsis :tooltip="false"> v-for="(audio, index) in collection.audios"
{{ audio.name }} class="collection-info-container-audioList-item"
</NEllipsis> >
</div> <div class="collection-info-container-audioList-item-index">
<n-input v-model:value="audio.name" v-if="isEditing"></n-input> <div>{{ index + 1 }}</div>
</div> </div>
<div class="collection-info-container-audioList-item-controller"> <div class="collection-info-container-audioList-item-info">
<PlayOutline class="collection-info-container-audioList-item-controller-item" <div
v-if="!isEditing" @click=" v-if="!isEditing"
emit('playAll', collection, index) class="collection-info-container-audioList-item-info-name"
"></PlayOutline> >
<TrashOutline class="collection-info-container-audioList-item-controller-item" <NEllipsis :tooltip="false">
v-if="isEditing" @click="handleDelete(index)"></TrashOutline> {{ audio.name }}
<ReorderFourOutline v-if="isEditing" </NEllipsis>
class="collection-info-container-audioList-item-controller-item collection-info-container-audioList-item-controller-item-drag"> </div>
</ReorderFourOutline> <n-input
</div> v-model:value="audio.name"
</div> v-if="isEditing"
</VueDraggable> ></n-input>
</div> </div>
</NScrollbar> <div
</div> class="collection-info-container-audioList-item-controller"
>
<PlayOutline
class="collection-info-container-audioList-item-controller-item"
v-if="!isEditing"
@click="emit('playAll', collection, index)"
></PlayOutline>
<TrashOutline
class="collection-info-container-audioList-item-controller-item"
v-if="isEditing"
@click="handleDelete(index)"
></TrashOutline>
<ReorderFourOutline
v-if="isEditing"
class="collection-info-container-audioList-item-controller-item collection-info-container-audioList-item-controller-item-drag"
></ReorderFourOutline>
</div>
</div>
</VueDraggable>
</div>
</NScrollbar>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { NScrollbar, NEllipsis, NInput } from 'naive-ui' import { NScrollbar, NEllipsis, NInput } from 'naive-ui'
import { VueDraggable } from 'vue-draggable-plus' import { VueDraggable } from 'vue-draggable-plus'
import { import {
ArrowBackOutline, ArrowBackOutline,
CaretForwardOutline, CaretForwardOutline,
ReorderFourOutline, ReorderFourOutline,
PlayOutline, PlayOutline,
CreateOutline, CreateOutline,
CheckmarkOutline, CheckmarkOutline,
TrashOutline TrashOutline
} from '@vicons/ionicons5' } from '@vicons/ionicons5'
import collectionType from '../types/collection' import collectionType from '../types/collection'
import { ref, watch } from 'vue' import { ref, watch } from 'vue'
const props = defineProps<{ const props = defineProps<{
collection: collectionType collection: collectionType
}>() }>()
const isEditing = ref(false) const isEditing = ref(false)
@@ -104,17 +142,20 @@ const clickDeleteCount = ref(0)
watch(isEditing, (v) => v && (clickDeleteCount.value = 0)) watch(isEditing, (v) => v && (clickDeleteCount.value = 0))
const handleDelete = (index: number) => { const handleDelete = (index: number) => {
props.collection.audios.splice(index, 1) props.collection.audios.splice(index, 1)
} }
const updateAudiosIndex = () => { const updateAudiosIndex = () => {
props.collection.audios = props.collection.audios.map((v, i) => ({ ...v, index: i })) props.collection.audios = props.collection.audios.map((v, i) => ({
...v,
index: i
}))
} }
const emit = defineEmits<{ const emit = defineEmits<{
exit: [] exit: []
deleteSelf: [] deleteSelf: []
playAll: [collection: collectionType, index?: number] playAll: [collection: collectionType, index?: number]
}>() }>()
</script> </script>
@@ -122,182 +163,182 @@ const emit = defineEmits<{
$ig: linear-gradient(90deg, #a1ee5e 0%, #00e3ae 100%); $ig: linear-gradient(90deg, #a1ee5e 0%, #00e3ae 100%);
.collection-info-container { .collection-info-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
background-color: #ffffff; background-color: #ffffff;
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
&-top { &-top {
height: 70px; height: 70px;
padding: 0 15px; padding: 0 15px;
background: $ig; background: $ig;
display: flex; display: flex;
align-items: center; align-items: center;
&-exit { &-exit {
width: 30px; width: 30px;
aspect-ratio: 1;
color: #063b2a;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
svg {
width: 25px;
aspect-ratio: 1; aspect-ratio: 1;
color: #063b2a; transition: width 0.25s ease;
}
&:hover {
svg {
width: 30px;
}
}
}
&-title {
display: flex;
margin-left: 10px;
margin-right: 100px;
flex: 1;
&-confirm {
margin-left: 10px;
width: 32px;
// color: #ffffff;
}
span {
user-select: none;
font-size: larger;
}
}
&-delete {
display: flex;
height: 25px;
position: absolute;
right: 28px;
color: red;
user-select: none;
cursor: pointer;
& > span {
position: relative;
top: 3px;
margin-left: 3px;
}
}
}
&-controller {
height: 50px;
padding: 0 15px;
display: flex;
align-items: center;
&-play {
display: flex;
align-items: center;
& > div {
cursor: pointer;
}
&-icon {
height: 30px;
width: 45px;
background: $ig;
border-radius: 10px;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
cursor: pointer;
svg { svg {
width: 25px; width: 30px;
aspect-ratio: 1; height: 25px;
transition: width 0.25s ease; color: aliceblue;
} }
}
&:hover { &-text {
svg {
width: 30px;
}
}
}
&-title {
display: flex;
margin-left: 10px;
margin-right: 100px;
flex: 1;
&-confirm {
margin-left: 10px;
width: 32px;
// color: #ffffff;
}
span {
user-select: none;
font-size: larger;
}
}
&-delete {
display: flex;
height: 25px;
position: absolute;
right: 28px;
color: red;
user-select: none; user-select: none;
margin-left: 10px;
font-size: larger;
}
}
&-right {
flex: 1;
display: flex;
align-items: center;
justify-content: flex-end;
& > div {
margin: 0 10px;
cursor: pointer; cursor: pointer;
height: 25px;
width: 25px;
color: #002911;
}
}
}
&>span { &-audioList {
position: relative; flex: 1;
top: 3px; color: #002911;
margin-left: 3px; padding-bottom: 88px;
&-item {
// padding: 0 20px;
padding-right: 7px;
display: flex;
height: 70px;
align-items: center;
&-index {
width: 50px;
user-select: none;
font-size: 24px;
text-align: right;
& > div {
margin: auto;
width: fit-content;
} }
} }
}
&-controller { &-info {
height: 50px;
padding: 0 15px;
display: flex;
align-items: center;
&-play {
display: flex;
align-items: center;
&>div {
cursor: pointer;
}
&-icon {
height: 30px;
width: 45px;
background: $ig;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
svg {
width: 30px;
height: 25px;
color: aliceblue;
}
}
&-text {
user-select: none;
margin-left: 10px;
font-size: larger;
}
}
&-right {
flex: 1; flex: 1;
display: flex; display: flex;
align-items: center; user-select: none;
justify-content: flex-end; overflow: hidden;
&>div { &-name {
margin: 0 10px; overflow: hidden;
cursor: pointer;
height: 25px;
width: 25px;
color: #002911;
} }
} }
}
&-audioList { &-controller {
flex: 1;
color: #002911;
padding-bottom: 88px;
&-item {
// padding: 0 20px;
padding-right: 7px;
display: flex; display: flex;
height: 70px;
align-items: center; align-items: center;
&-index { &-item {
width: 50px; width: 30px;
user-select: none; cursor: pointer;
font-size: 24px; margin: 0 5px;
text-align: right;
&>div {
margin: auto;
width: fit-content;
}
} }
}
&-info { }
flex: 1; }
display: flex;
user-select: none;
overflow: hidden;
&-name {
overflow: hidden;
}
}
&-controller {
display: flex;
align-items: center;
&-item {
width: 30px;
cursor: pointer;
margin: 0 5px;
}
}
}
}
} }
.isDragging { .isDragging {
opacity: 0.5; opacity: 0.5;
} }
</style> </style>
@@ -1,123 +1,138 @@
<template> <template>
<div class="aplayer-list-top"> <div class="aplayer-list-top">
<div @click="loopModeToggle" class="aplayer-list-top-loopMode"> <div
<component @click="loopModeToggle"
:is="loopModeMap[loopMode].icon" class="aplayer-list-top-loopMode"
class="aplayer-list-top-loopMode-icon"></component> >
<span class="aplayer-list-top-loopMode-name"> <component
{{ loopModeMap[loopMode].name }} :is="loopModeMap[loopMode].icon"
class="aplayer-list-top-loopMode-icon"
></component>
<span class="aplayer-list-top-loopMode-name">
{{ loopModeMap[loopMode].name }}
</span>
</div>
<div class="aplayer-list-top-buttons">
<AddCircleOutline
v-if="onSaveCollection"
class="aplayer-list-top-buttons-icon"
@click="onSaveCollection(ap.list.audios)"
></AddCircleOutline>
</div>
<span></span>
</div>
<ol
:style="{ maxHeight: `calc( ${ap.options.listMaxHeight} - 30px )` }"
:class="[
!isDragging ? 'miaoMusic-ol-isDragging' : 'miaoMusic-ol-notDragging'
]"
:key="refreshKey"
ref="ol"
>
<VueDraggable
v-model="ap.list.audios"
@start="onDragStart"
@end="onDragEnd"
item-key="id"
handle=".aplayer-list-control-btn-reorder"
ghostClass="iSDragging"
:animation="150"
>
<!-- <miaoLazyDiv :min-height="'32px'" auto-height> -->
<li
v-for="(element, index) in ap.list.audios"
:class="[activeAudioIndex == index ? 'aplayer-list-light' : '']"
class="aplayer-list-new"
:key="element.id"
>
<span
class="aplayer-list-cur"
:style="{ backgroundColor: apTheme }"
></span>
<span class="aplayer-list-index">{{ index + 1 }}</span>
<span class="aplayer-list-title">{{ element.name }}</span>
<div class="aplayer-list-control">
<div
v-if="isVideo(element)"
class="aplayer-list-control-btn aplayer-list-control-btn-hover aplayer-list-control-btn-play"
@click.stop="onPlayVideo && onPlayVideo(element)"
>
<VideocamOutline class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn aplayer-list-control-btn-hover aplayer-list-control-btn-play"
@click.stop="switchAudio(index)"
>
<component
:is="
activeAudioIndex == index && !isPaused
? PauseOutline
: PlayOutline
"
class="aplayer-list-control-btn-svg"
></component>
</div>
<div
class="aplayer-list-control-btn aplayer-list-control-btn-hover"
@click.stop="switchAudio(index)"
v-if="false"
>
<HeartOutline class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn"
@click.stop="listAudioUp(index)"
v-if="false"
>
<ChevronUpOutline class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn"
@click.stop="listAudioDown(index)"
v-if="false"
>
<ChevronDownOutline class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn aplayer-list-control-btn-hover"
@click.stop="listAudioRemove(index)"
>
<CloseOutline class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn aplayer-list-control-btn-reorder"
>
<ReorderFourOutline class="aplayer-list-control-btn-svg" />
</div>
</div>
<span
class="aplayer-list-author"
v-show="element.artist !== 'Audio artist1'"
>
{{ element.artist }}
</span> </span>
</div> </li>
<div class="aplayer-list-top-buttons"> <!-- </miaoLazyDiv> -->
<AddCircleOutline </VueDraggable>
v-if="onSaveCollection" </ol>
class="aplayer-list-top-buttons-icon"
@click="onSaveCollection(ap.list.audios)"></AddCircleOutline>
</div>
<span></span>
</div>
<ol
:style="{ maxHeight: `calc( ${ap.options.listMaxHeight} - 30px )` }"
:class="[
!isDragging ? 'miaoMusic-ol-isDragging' : 'miaoMusic-ol-notDragging'
]"
:key="refreshKey"
ref="ol">
<VueDraggable
v-model="ap.list.audios"
@start="onDragStart"
@end="onDragEnd"
item-key="id"
handle=".aplayer-list-control-btn-reorder"
ghostClass="iSDragging"
:animation="150">
<!-- <miaoLazyDiv :min-height="'32px'" auto-height> -->
<li
v-for="(element, index) in ap.list.audios"
:class="[activeAudioIndex == index ? 'aplayer-list-light' : '']"
class="aplayer-list-new"
:key="element.id">
<span
class="aplayer-list-cur"
:style="{ backgroundColor: apTheme }"></span>
<span class="aplayer-list-index">{{ index + 1 }}</span>
<span class="aplayer-list-title">{{ element.name }}</span>
<div class="aplayer-list-control">
<div
v-if="isVideo(element)"
class="aplayer-list-control-btn aplayer-list-control-btn-hover aplayer-list-control-btn-play"
@click.stop="onPlayVideo && onPlayVideo(element)">
<VideocamOutline class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn aplayer-list-control-btn-hover aplayer-list-control-btn-play"
@click.stop="switchAudio(index)">
<component
:is="
activeAudioIndex == index && !isPaused
? PauseOutline
: PlayOutline
"
class="aplayer-list-control-btn-svg"></component>
</div>
<div
class="aplayer-list-control-btn aplayer-list-control-btn-hover"
@click.stop="switchAudio(index)"
v-if="false">
<HeartOutline class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn"
@click.stop="listAudioUp(index)"
v-if="false">
<ChevronUpOutline
class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn"
@click.stop="listAudioDown(index)"
v-if="false">
<ChevronDownOutline
class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn aplayer-list-control-btn-hover"
@click.stop="listAudioRemove(index)">
<CloseOutline class="aplayer-list-control-btn-svg" />
</div>
<div
class="aplayer-list-control-btn aplayer-list-control-btn-reorder">
<ReorderFourOutline
class="aplayer-list-control-btn-svg" />
</div>
</div>
<span
class="aplayer-list-author"
v-show="element.artist !== 'Audio artist1'">
{{ element.artist }}
</span>
</li>
<!-- </miaoLazyDiv> -->
</VueDraggable>
</ol>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue' import { computed, nextTick, onMounted, ref } from 'vue'
import { import {
ChevronUpOutline, ChevronUpOutline,
ChevronDownOutline, ChevronDownOutline,
CloseOutline, CloseOutline,
ReorderFourOutline, ReorderFourOutline,
PlayOutline, PlayOutline,
HeartOutline, HeartOutline,
VideocamOutline, VideocamOutline,
PauseOutline, PauseOutline,
ListCircleOutline, ListCircleOutline,
ListOutline, ListOutline,
HeadsetOutline, HeadsetOutline,
LogoOctocat, LogoOctocat,
AddCircleOutline AddCircleOutline
} from '@vicons/ionicons5' } from '@vicons/ionicons5'
import { VueDraggable } from 'vue-draggable-plus' import { VueDraggable } from 'vue-draggable-plus'
@@ -127,9 +142,9 @@ import apType, { audioType } from '../../types/ap'
import { aplayerMiaoOption } from '../../hooks/aplayerMiao' import { aplayerMiaoOption } from '../../hooks/aplayerMiao'
const props = defineProps< const props = defineProps<
{ {
ap: apType ap: apType
} & aplayerMiaoOption } & aplayerMiaoOption
>() >()
const apRef = ref(props.ap) const apRef = ref(props.ap)
@@ -141,309 +156,309 @@ const refreshKey = ref(Math.random())
const isDragging = ref(false) const isDragging = ref(false)
const apTheme = computed( const apTheme = computed(
() => () =>
props.ap.list.audios[activeAudioIndex.value].theme ?? props.ap.list.audios[activeAudioIndex.value].theme ??
props.ap.options.theme props.ap.options.theme
) )
const activeAudioIndex = computed(() => props.ap.list.index) const activeAudioIndex = computed(() => props.ap.list.index)
const isPaused = ref(false) const isPaused = ref(false)
props.ap.on('play', () => { props.ap.on('play', () => {
nextTick(() => { nextTick(() => {
isPaused.value = false isPaused.value = false
}) })
}) })
props.ap.on('pause', () => { props.ap.on('pause', () => {
isPaused.value = true isPaused.value = true
}) })
props.ap.on('listswitch', (...args: any) => { props.ap.on('listswitch', (...args: any) => {
// 手动触发更新,不然监听不到 // 手动触发更新,不然监听不到
props.ap.list.index = args[0].index as number props.ap.list.index = args[0].index as number
}) })
const refresh = () => { const refresh = () => {
const top = ol.value?.scrollTop const top = ol.value?.scrollTop
refreshKey.value = Math.random() refreshKey.value = Math.random()
nextTick(() => { nextTick(() => {
ol.value?.scrollTo({ ol.value?.scrollTo({
top top
}) })
}) })
} }
props.ap.on('listremove', refresh) props.ap.on('listremove', refresh)
props.ap.on('listadd', refresh) props.ap.on('listadd', refresh)
const switchAudio = (index: number) => { const switchAudio = (index: number) => {
if (index === activeAudioIndex.value) { if (index === activeAudioIndex.value) {
if (props.ap.paused) { if (props.ap.paused) {
props.ap.play() props.ap.play()
} else { } else {
props.ap.pause() props.ap.pause()
} }
props.ap.paused = props.ap.paused props.ap.paused = props.ap.paused
return return
} }
props.ap.list.switch(index) props.ap.list.switch(index)
} }
const listRefreshIndex = (curr: audioType) => { const listRefreshIndex = (curr: audioType) => {
for (let index in props.ap.list.audios) { for (let index in props.ap.list.audios) {
if (props.ap.list.audios[index] === curr) { if (props.ap.list.audios[index] === curr) {
props.ap.list.index = parseInt(index) props.ap.list.index = parseInt(index)
return return
} }
} }
} }
const listAudioUp = (index: number) => { const listAudioUp = (index: number) => {
const arr = props.ap.list.audios const arr = props.ap.list.audios
const len = arr.length const len = arr.length
const curr = props.ap.list.audios[props.ap.list.index] const curr = props.ap.list.audios[props.ap.list.index]
if (index === 0) { if (index === 0) {
const _item = arr.shift() const _item = arr.shift()
_item && arr.push(_item) _item && arr.push(_item)
} else { } else {
const pre: number = (len - 1 + index) % len const pre: number = (len - 1 + index) % len
const _pre = arr[index] const _pre = arr[index]
arr[index] = arr[pre] arr[index] = arr[pre]
arr[pre] = _pre arr[pre] = _pre
} }
listRefreshIndex(curr) listRefreshIndex(curr)
} }
const listAudioDown = (index: number) => { const listAudioDown = (index: number) => {
const arr = props.ap.list.audios const arr = props.ap.list.audios
const len = arr.length const len = arr.length
const curr = props.ap.list.audios[props.ap.list.index] const curr = props.ap.list.audios[props.ap.list.index]
if (index === len - 1) { if (index === len - 1) {
const _item = arr.pop() const _item = arr.pop()
_item && arr.unshift(_item) _item && arr.unshift(_item)
} else { } else {
const pre: number = (len + 1 + index) % len const pre: number = (len + 1 + index) % len
const _pre = arr[index] const _pre = arr[index]
arr[index] = arr[pre] arr[index] = arr[pre]
arr[pre] = _pre arr[pre] = _pre
} }
listRefreshIndex(curr) listRefreshIndex(curr)
} }
const listAudioRemove = (index: number) => { const listAudioRemove = (index: number) => {
props.ap.list.remove(index) props.ap.list.remove(index)
} }
const { onDragStart, onDragEnd } = (() => { const { onDragStart, onDragEnd } = (() => {
let curr: audioType let curr: audioType
return { return {
onDragStart: () => { onDragStart: () => {
isDragging.value = true isDragging.value = true
curr = props.ap.list.audios[props.ap.list.index] curr = props.ap.list.audios[props.ap.list.index]
}, },
onDragEnd: () => { onDragEnd: () => {
listRefreshIndex(curr) listRefreshIndex(curr)
nextTick(() => { nextTick(() => {
isDragging.value = false isDragging.value = false
}) })
} }
} }
})() })()
const isVideo = (element: audioType) => { const isVideo = (element: audioType) => {
for (let end of ['mp4']) { for (let end of ['mp4']) {
if (element.name.endsWith(end)) { if (element.name.endsWith(end)) {
return true return true
} }
} }
return false return false
} }
const loopModeMap = { const loopModeMap = {
0: { name: '列表循环', icon: ListCircleOutline }, 0: { name: '列表循环', icon: ListCircleOutline },
1: { name: '单曲循环', icon: HeadsetOutline }, 1: { name: '单曲循环', icon: HeadsetOutline },
2: { name: '列表播放', icon: ListOutline }, 2: { name: '列表播放', icon: ListOutline },
3: { name: '随机播放', icon: LogoOctocat } 3: { name: '随机播放', icon: LogoOctocat }
} }
const loopMode = computed(() => { const loopMode = computed(() => {
if (apRef.value.options.order === 'list') { if (apRef.value.options.order === 'list') {
switch (apRef.value.options.loop) { switch (apRef.value.options.loop) {
case 'all': case 'all':
return 0 return 0
case 'one': case 'one':
return 1 return 1
case 'none': case 'none':
return 2 return 2
} }
} }
return 3 return 3
}) })
const loopModeToggle = () => { const loopModeToggle = () => {
const ops = apRef.value.options const ops = apRef.value.options
if (ops.order === 'random') { if (ops.order === 'random') {
ops.order = 'list' ops.order = 'list'
} else { } else {
switch (ops.loop) { switch (ops.loop) {
case 'all': { case 'all': {
ops.loop = 'one' ops.loop = 'one'
break break
} }
case 'one': { case 'one': {
ops.loop = 'none' ops.loop = 'none'
break break
} }
case 'none': { case 'none': {
ops.loop = 'all' ops.loop = 'all'
ops.order = 'random' ops.order = 'random'
break break
} }
} }
} }
} }
onMounted(() => { onMounted(() => {
console.log(props.ap) console.log(props.ap)
}) })
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.aplayer-list-new { .aplayer-list-new {
height: fit-content !important; height: fit-content !important;
cursor: default !important; cursor: default !important;
.aplayer-list-cur { .aplayer-list-cur {
height: calc(100% - 8px) !important; height: calc(100% - 8px) !important;
} }
.aplayer-list-index { .aplayer-list-index {
display: inline-block; display: inline-block;
width: 20px; width: 20px;
margin-right: 4px !important; margin-right: 4px !important;
cursor: default !important; cursor: default !important;
} }
} }
.aplayer-list-control { .aplayer-list-control {
float: right; float: right;
height: 32px; height: 32px;
display: flex; display: flex;
align-items: center; align-items: center;
&-btn { &-btn {
width: 25px; width: 25px;
height: 25px; height: 25px;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
cursor: pointer; cursor: pointer;
&-svg { &-svg {
width: 20px; width: 20px;
aspect-ratio: 1; aspect-ratio: 1;
transition: all 0.1s ease; transition: all 0.1s ease;
} }
} }
&-btn-hover { &-btn-hover {
.aplayer-list-control-btn-svg { .aplayer-list-control-btn-svg {
&:hover { &:hover {
width: 24px; width: 24px;
} }
} }
} }
} }
.aplayer-list-top { .aplayer-list-top {
height: 30px; height: 30px;
// width: auto; // width: auto;
// max-width: 100%; // max-width: 100%;
position: relative; position: relative;
border-bottom: 1px solid #e9e9e9; border-bottom: 1px solid #e9e9e9;
display: flex; display: flex;
justify-items: baseline; justify-items: baseline;
align-items: center; align-items: center;
padding: 0 10px; padding: 0 10px;
.aplayer-list-top-loopMode { .aplayer-list-top-loopMode {
text-align: center; text-align: center;
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
cursor: pointer; cursor: pointer;
float: left; float: left;
// background-color: #f9f9f9; // background-color: #f9f9f9;
scale: 1; scale: 1;
transition: scale 0.15s ease; transition: scale 0.15s ease;
&-icon { &-icon {
width: 20px; width: 20px;
aspect-ratio: 1; aspect-ratio: 1;
transform: translateY(1px); transform: translateY(1px);
fill: #000; fill: #000;
path { path {
fill: #000 !important; fill: #000 !important;
} }
} }
&-name { &-name {
margin-left: 5px; margin-left: 5px;
} }
&:hover { &:hover {
scale: 1.1; scale: 1.1;
} }
} }
.aplayer-list-top-buttons { .aplayer-list-top-buttons {
display: inline-flex; display: inline-flex;
position: absolute; position: absolute;
right: 10px; right: 10px;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
scale: 1; scale: 1;
transition: scale 0.15s ease; transition: scale 0.15s ease;
&-icon { &-icon {
width: 20px; width: 20px;
aspect-ratio: 1; aspect-ratio: 1;
cursor: pointer; cursor: pointer;
} }
&:hover { &:hover {
scale: 1.1; scale: 1.1;
} }
} }
} }
</style> </style>
<style lang="scss"> <style lang="scss">
.aplayer svg circle, .aplayer svg circle,
.aplayer .aplayer-list-new svg path { .aplayer .aplayer-list-new svg path {
fill: #ffffff00; fill: #ffffff00;
} }
.iSDragging { .iSDragging {
opacity: 0.5; opacity: 0.5;
// background: #60e8a2 !important; // background: #60e8a2 !important;
} }
.aplayer-list-light { .aplayer-list-light {
background: unset !important; background: unset !important;
.aplayer-list-title { .aplayer-list-title {
color: #60e8a2; color: #60e8a2;
} }
} }
.aplayer .aplayer-list .miaoMusic-ol-isDragging li:hover { .aplayer .aplayer-list .miaoMusic-ol-isDragging li:hover {
background: #efefef !important; background: #efefef !important;
} }
.miaoMusicDrag-move, .miaoMusicDrag-move,
.miaoMusicDrag-enter-active, .miaoMusicDrag-enter-active,
.miaoMusicDrag-leave-active { .miaoMusicDrag-leave-active {
transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1); transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
} }
.miaoMusicDrag-enter-from, .miaoMusicDrag-enter-from,
.miaoMusicDrag-leave-to { .miaoMusicDrag-leave-to {
opacity: 0; opacity: 0;
transform: scaleY(0.01) translate(30px, 0); transform: scaleY(0.01) translate(30px, 0);
} }
.miaoMusicDrag-leave-active { .miaoMusicDrag-leave-active {
position: absolute; position: absolute;
} }
</style> </style>
@@ -1,30 +1,37 @@
<template> <template>
<div class="collection" @click="emit('onenter')"> <div
<div class="collection-cover" @click.stop="emit('onPlay')"> class="collection"
<img @click="emit('onenter')"
v-if="item.coverUrl" >
class="collection-cover-img" <div
:src="item.coverUrl" /> class="collection-cover"
<div class="collection-cover-play"> @click.stop="emit('onPlay')"
<Play></Play> >
</div> <img
</div> v-if="item.coverUrl"
<div class="collection-info"> class="collection-cover-img"
<div class="collection-info-name"> :src="item.coverUrl"
<span class="collection-info-name-ellipsis"> />
<span> <div class="collection-cover-play">
{{ item.name }} <Play></Play>
</span> </div>
</span> </div>
</div> <div class="collection-info">
<div class="collection-info-stats"> <div class="collection-info-name">
<span class="collection-info-stats-time">{{ dateStr }}</span> <span class="collection-info-name-ellipsis">
<span class="collection-info-stats-count"> <span>
{{ `共${item.audios.length}首` }} {{ item.name }}
</span> </span>
</div> </span>
</div> </div>
</div> <div class="collection-info-stats">
<span class="collection-info-stats-time">{{ dateStr }}</span>
<span class="collection-info-stats-count">
{{ `共${item.audios.length}首` }}
</span>
</div>
</div>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -34,90 +41,92 @@ import dateFormatter from '@/hooks/dateFormatter'
import { Play } from '@vicons/ionicons5' import { Play } from '@vicons/ionicons5'
const props = defineProps<{ const props = defineProps<{
item: collectionType item: collectionType
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
onPlay: [] onPlay: []
onenter: [] onenter: []
}>() }>()
const dateStr = computed(() => const dateStr = computed(() =>
dateFormatter(new Date(props.item.createTime), 'yyyy-MM-dd') dateFormatter(new Date(props.item.createTime), 'yyyy-MM-dd')
) )
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.collection { .collection {
height: 50px; height: 50px;
position: relative; position: relative;
display: flex; display: flex;
box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), box-shadow:
0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05); 0 3px 6px -4px rgba(0, 0, 0, 0.12),
border-radius: 5px; 0 6px 16px 0 rgba(0, 0, 0, 0.08),
overflow: hidden; 0 9px 28px 8px rgba(0, 0, 0, 0.05);
transition: height 0.25s ease; border-radius: 5px;
cursor: pointer; overflow: hidden;
user-select: none; transition: height 0.25s ease;
cursor: pointer;
user-select: none;
&:not(&:last-child) { &:not(&:last-child) {
margin-bottom: 15px; margin-bottom: 15px;
} }
.collection-cover { .collection-cover {
width: 50px; width: 50px;
height: 50px; height: 50px;
aspect-ratio: 1; aspect-ratio: 1;
background-color: #60e8a2; background-color: #60e8a2;
margin-right: 5px; margin-right: 5px;
.collection-cover-play { .collection-cover-play {
width: 25px; width: 25px;
height: 15px;
background-color: #d1d1d1b2;
position: absolute;
bottom: 5px;
left: 5px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 3px;
svg {
height: 15px; height: 15px;
background-color: #d1d1d1b2; color: #fff;
position: absolute; }
bottom: 5px; }
left: 5px; }
display: flex; .collection-info {
justify-content: center; position: relative;
align-items: center; width: calc(100% - 60px);
border-radius: 3px; display: flex;
svg { flex-direction: column;
height: 15px; justify-content: center;
color: #fff; .collection-info-name {
} max-width: 100%;
} overflow: hidden;
} &-ellipsis {
.collection-info {
position: relative;
width: calc(100% - 60px);
display: flex;
flex-direction: column;
justify-content: center;
.collection-info-name {
max-width: 100%;
overflow: hidden; overflow: hidden;
&-ellipsis { white-space: nowrap;
overflow: hidden; display: inline-block;
white-space: nowrap; vertical-align: bottom;
display: inline-block; max-width: 100%;
vertical-align: bottom; text-overflow: ellipsis;
max-width: 100%;
text-overflow: ellipsis;
span {
white-space: nowrap;
text-wrap: nowrap;
text-overflow: ellipsis;
}
}
}
.collection-info-stats {
text-wrap: nowrap;
span { span {
font-size: smaller; white-space: nowrap;
text-wrap: nowrap;
text-overflow: ellipsis;
} }
.collection-info-stats-time { }
margin-right: 10px; }
} .collection-info-stats {
} text-wrap: nowrap;
} span {
font-size: smaller;
}
.collection-info-stats-time {
margin-right: 10px;
}
}
}
} }
</style> </style>
+88 -83
View File
@@ -1,51 +1,56 @@
<template> <template>
<div class="miaoMusic-main"> <div class="miaoMusic-main">
<NScrollbar> <NScrollbar>
<div class="miaoMusic-main-collectionsList"> <div class="miaoMusic-main-collectionsList">
<div class="miaoMusic-main-collectionsList-title">自建歌单</div> <div class="miaoMusic-main-collectionsList-title">自建歌单</div>
<VueDraggable <VueDraggable
v-if="collections" v-if="collections"
v-model="collections" v-model="collections"
:animation="150" :animation="150"
:delay="100" :delay="100"
ghostClass="iSDragging"> ghostClass="iSDragging"
<collection >
v-for="item in collections" <collection
:item="item" v-for="item in collections"
@on-play="handleCollectionsPlay(item)" :item="item"
@onenter="handleCollectionEnter(item)"></collection> @on-play="handleCollectionsPlay(item)"
</VueDraggable> @onenter="handleCollectionEnter(item)"
<n-empty ></collection>
description="空空如也~" </VueDraggable>
size="huge" <n-empty
style="margin-top: 200px" description="空空如也~"
v-if="!data || data?.length === 0"> size="huge"
<template #icon> style="margin-top: 200px"
<n-icon> v-if="!data || data?.length === 0"
<HandLeftOutline /> >
</n-icon> <template #icon>
</template> <n-icon>
<template #extra> <HandLeftOutline />
<n-button </n-icon>
size="small" </template>
type="primary" <template #extra>
@click="emit('newCollection')"> <n-button
立刻创建 size="small"
</n-button> type="primary"
</template> @click="emit('newCollection')"
</n-empty> >
</div> 立刻创建
</NScrollbar> </n-button>
<Transition name="slide-fade"> </template>
<collectionInfo </n-empty>
class="miaoMusic-main-collection" </div>
:collection="currCollection" </NScrollbar>
v-if="currCollection" <Transition name="slide-fade">
@exit="handleCollectionEnter(undefined)" <collectionInfo
@delete-self="handleCollectionDelete()" class="miaoMusic-main-collection"
@play-all="handleCollectionsPlay"></collectionInfo> :collection="currCollection"
</Transition> v-if="currCollection"
</div> @exit="handleCollectionEnter(undefined)"
@delete-self="handleCollectionDelete()"
@play-all="handleCollectionsPlay"
></collectionInfo>
</Transition>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -59,75 +64,75 @@ import { NScrollbar, NEmpty, NButton } from 'naive-ui'
import { HandLeftOutline } from '@vicons/ionicons5' import { HandLeftOutline } from '@vicons/ionicons5'
const props = defineProps<{ const props = defineProps<{
ap: apType ap: apType
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
newCollection: [] newCollection: []
}>() }>()
const collections = defineModel<collectionType[]>('data') const collections = defineModel<collectionType[]>('data')
const currCollection = ref<collectionType>() const currCollection = ref<collectionType>()
const playCollection = (collection: collectionType, index?: number) => { const playCollection = (collection: collectionType, index?: number) => {
const ap = props.ap const ap = props.ap
console.log({ collection, ap }) console.log({ collection, ap })
// clear有bug // clear有bug
while (ap.list.audios.length !== 0) { while (ap.list.audios.length !== 0) {
ap.list.remove(0) ap.list.remove(0)
} }
ap.list.add(collection.audios) ap.list.add(collection.audios)
index && ap.list.switch(index) index && ap.list.switch(index)
ap.play() ap.play()
} }
const handleCollectionsPlay = (item: collectionType, index?: number) => { const handleCollectionsPlay = (item: collectionType, index?: number) => {
playCollection(item, index) playCollection(item, index)
} }
const handleCollectionEnter = (item: collectionType | undefined) => { const handleCollectionEnter = (item: collectionType | undefined) => {
currCollection.value = item currCollection.value = item
} }
const handleCollectionDelete = () => { const handleCollectionDelete = () => {
collections.value && collections.value &&
collections.value.splice( collections.value.splice(
collections.value.findIndex((v) => v === currCollection.value), collections.value.findIndex((v) => v === currCollection.value),
1 1
) )
currCollection.value = undefined currCollection.value = undefined
} }
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.miaoMusic-main { .miaoMusic-main {
position: relative; position: relative;
max-height: 100%; max-height: 100%;
height: 100%; height: 100%;
.miaoMusic-main-collectionsList { .miaoMusic-main-collectionsList {
padding: 15px 20px 88px; padding: 15px 20px 88px;
&-title { &-title {
font-size: larger; font-size: larger;
letter-spacing: 1px; letter-spacing: 1px;
margin-bottom: 10px; margin-bottom: 10px;
user-select: none; user-select: none;
} }
} }
} }
.slide-fade-enter-active { .slide-fade-enter-active {
transition: all 0.15s ease-out; transition: all 0.15s ease-out;
} }
.slide-fade-leave-active { .slide-fade-leave-active {
transition: all 0.15s cubic-bezier(1, 0.5, 0.8, 1); transition: all 0.15s cubic-bezier(1, 0.5, 0.8, 1);
} }
.slide-fade-enter-from, .slide-fade-enter-from,
.slide-fade-leave-to { .slide-fade-leave-to {
transform: translateX(200px); transform: translateX(200px);
opacity: 0; opacity: 0;
} }
.isDragging { .isDragging {
opacity: 0.5; opacity: 0.5;
} }
</style> </style>
+38 -38
View File
@@ -1,45 +1,45 @@
export type audioType = { export type audioType = {
url: string url: string
artist?: string artist?: string
cover?: string cover?: string
name: string name: string
theme?: string theme?: string
id?: number id?: number
index: number index: number
} }
type apType = { type apType = {
paused: boolean paused: boolean
list: { list: {
audios: audioType[] audios: audioType[]
index: number index: number
switch: (index: number) => void switch: (index: number) => void
remove: (index: number) => void remove: (index: number) => void
add: (audios: audioType[]) => void add: (audios: audioType[]) => void
refreshAudioIndex: () => void refreshAudioIndex: () => void
hide: () => void hide: () => void
clear: () => void clear: () => void
} }
container: HTMLDivElement container: HTMLDivElement
on: (event: string, callback: () => void) => void on: (event: string, callback: () => void) => void
options: { options: {
audio: audioType[] audio: audioType[]
autoplay: boolean autoplay: boolean
volume: number volume: number
theme: string theme: string
mini: boolean mini: boolean
fixed: boolean fixed: boolean
mutex: boolean mutex: boolean
lrcType: number lrcType: number
preload: 'auto' preload: 'auto'
loop: 'all' | 'one' | 'none' loop: 'all' | 'one' | 'none'
order: 'list' | 'random' order: 'list' | 'random'
listMaxHeight: string listMaxHeight: string
storageName: 'aplayer-setting' storageName: 'aplayer-setting'
} }
destroy: () => {} destroy: () => {}
pause: () => void pause: () => void
play: () => void play: () => void
} }
export default apType export default apType
+10 -10
View File
@@ -1,14 +1,14 @@
import type { audioType } from "./ap"; import type { audioType } from './ap'
export type collectionItemType = {} & audioType; export type collectionItemType = {} & audioType
export type collectionType = { export type collectionType = {
id: number; id: number
name: string; name: string
intro: string; intro: string
createTime: Date; createTime: Date
coverUrl?: string; coverUrl?: string
audios: collectionItemType[]; audios: collectionItemType[]
}; }
export default collectionType; export default collectionType
+14 -15
View File
@@ -2,24 +2,23 @@ import { registerComponentOption } from '@/class/PluginCenter'
import DocumentText from '@vicons/ionicons5/es/DocumentText' import DocumentText from '@vicons/ionicons5/es/DocumentText'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: 'miaoPDF', key: 'miaoPDF',
name: 'PDF浏览', name: 'PDF浏览',
icon: DocumentText, icon: DocumentText,
getComponent: async () => getComponent: async () =>
(await import('@/plugins/miaoPDF/miaoPDF.vue')).default, (await import('@/plugins/miaoPDF/miaoPDF.vue')).default,
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vDirs.length !== 0) { if (vDirs.length !== 0) {
return false return false
} }
if (vFiles.length !== 1) { if (vFiles.length !== 1) {
return false return false
} }
return vFiles[0].name.endsWith('pdf') return vFiles[0].name.endsWith('pdf')
} }
} }
export default pluginConfig export default pluginConfig
import { PluginExportType } from '@/types/type' import { PluginExportType } from '@/types/type'
export const type = PluginExportType.component export const type = PluginExportType.component
+163 -156
View File
@@ -1,54 +1,61 @@
<template> <template>
<miao-message-provider ref="miaoMessageRef"> <miao-message-provider ref="miaoMessageRef">
<div class="miao-container"> <div class="miao-container">
<div class="miao-container-topBar"> <div class="miao-container-topBar">
<div <div
class="miao-container-topBar-btn" class="miao-container-topBar-btn"
@click="() => handleZoom(10)" @click="() => handleZoom(10)"
title="快速缩小"> title="快速缩小"
-- >
</div> --
<div
class="miao-container-topBar-btn"
@click="() => handleZoom()"
title="缩小">
-
</div>
<div
class="miao-container-topBar-btn"
@click="() => handleResetMargin()"
title="还原">
还原缩放
</div>
<div
class="miao-container-topBar-btn"
@click="() => handleShrink()"
title="放大">
+
</div>
<div
class="miao-container-topBar-btn"
@click="() => handleShrink(10)"
title="快速放大">
++
</div>
</div> </div>
<NScrollbar> <div
<div class="miao-container-topBar-btn"
class="miao-container-pdf" @click="() => handleZoom()"
:style="{ title="缩小"
alignItems: pdfMargin < 0 ? 'baseline' : 'center' >
}"> -
<div </div>
ref="pdfEl" <div
class="miao-container-pdf-content" class="miao-container-topBar-btn"
:style="{ @click="() => handleResetMargin()"
width: `calc( 100% - ${pdfMargin}px)` title="还原"
}"></div> >
</div> 还原缩放
</NScrollbar> </div>
</div> <div
</miao-message-provider> class="miao-container-topBar-btn"
@click="() => handleShrink()"
title="放大"
>
+
</div>
<div
class="miao-container-topBar-btn"
@click="() => handleShrink(10)"
title="快速放大"
>
++
</div>
</div>
<NScrollbar>
<div
class="miao-container-pdf"
:style="{
alignItems: pdfMargin < 0 ? 'baseline' : 'center'
}"
>
<div
ref="pdfEl"
class="miao-container-pdf-content"
:style="{
width: `calc( 100% - ${pdfMargin}px)`
}"
></div>
</div>
</NScrollbar>
</div>
</miao-message-provider>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -59,7 +66,7 @@ import { VirtualFile } from '@/class/VirtualDirectory'
import { NScrollbar } from 'naive-ui' import { NScrollbar } from 'naive-ui'
const currentFiles = defineModel<VirtualFile[]>('currentFiles', { const currentFiles = defineModel<VirtualFile[]>('currentFiles', {
required: true required: true
}) })
const pdfEl = ref<HTMLDivElement>() const pdfEl = ref<HTMLDivElement>()
@@ -72,130 +79,130 @@ const pdfPageCount = ref<number>(-1)
const canvasList = shallowReactive<HTMLCanvasElement[]>([]) const canvasList = shallowReactive<HTMLCanvasElement[]>([])
const handleZoom = (index?: number) => { const handleZoom = (index?: number) => {
const _index = index ?? 1 const _index = index ?? 1
pdfMargin.value += 10 * _index pdfMargin.value += 10 * _index
} }
const handleShrink = (index?: number) => { const handleShrink = (index?: number) => {
const _index = index ?? 1 const _index = index ?? 1
// if (pdfMargin.value - 10 * _index <= 0) { // if (pdfMargin.value - 10 * _index <= 0) {
// return pdfMargin.value = 0 // return pdfMargin.value = 0
// } // }
pdfMargin.value -= 10 * _index pdfMargin.value -= 10 * _index
} }
const handleResetMargin = () => { const handleResetMargin = () => {
pdfMargin.value = 0 pdfMargin.value = 0
} }
onMounted(async () => { onMounted(async () => {
const setLoadingMessage = miaoMessageRef.value?.alertTip('加载PDF插件中', { const setLoadingMessage = miaoMessageRef.value?.alertTip('加载PDF插件中', {
type: 'info', type: 'info',
timeout: -1 timeout: -1
}) })
const pdfSrc = currentFiles.value[0].url const pdfSrc = currentFiles.value[0].url
// @ts-ignore // @ts-ignore
const PDFJS = await import('pdfjs-dist/build/pdf.mjs') const PDFJS = await import('pdfjs-dist/build/pdf.mjs')
if (typeof window !== 'undefined' && 'Worker' in window) { if (typeof window !== 'undefined' && 'Worker' in window) {
PDFJS.GlobalWorkerOptions.workerPort = new PdfjsWorker() PDFJS.GlobalWorkerOptions.workerPort = new PdfjsWorker()
} }
// 加载文档 // 加载文档
let loadingTask = PDFJS.getDocument({ url: pdfSrc }) let loadingTask = PDFJS.getDocument({ url: pdfSrc })
loadingTask.__PDFDocumentLoadingTask = true loadingTask.__PDFDocumentLoadingTask = true
const pdf = await loadingTask.promise // 使用await等待加载完毕 const pdf = await loadingTask.promise // 使用await等待加载完毕
pdfPageCount.value = pdf.numPages pdfPageCount.value = pdf.numPages
// 循环渲染每一页 // 循环渲染每一页
for (let i = 1; i <= pdf.numPages; i++) { for (let i = 1; i <= pdf.numPages; i++) {
setLoadingMessage && setLoadingMessage(`渲染进度:${i}/${pdf.numPages}`) setLoadingMessage && setLoadingMessage(`渲染进度:${i}/${pdf.numPages}`)
const page = await pdf.getPage(i) const page = await pdf.getPage(i)
let pixelRatio = 3 let pixelRatio = 3
let viewport = page.getViewport({ scale: 1 }) let viewport = page.getViewport({ scale: 1 })
// 使用canvas渲染 // 使用canvas渲染
let canvas = window.document.createElement('canvas') let canvas = window.document.createElement('canvas')
canvasList.push(canvas) canvasList.push(canvas)
// @ts-ignore // @ts-ignore
pdfEl.value.appendChild(canvas) pdfEl.value.appendChild(canvas)
canvas.width = viewport.width * pixelRatio // 计算宽度 canvas.width = viewport.width * pixelRatio // 计算宽度
canvas.height = viewport.height * pixelRatio canvas.height = viewport.height * pixelRatio
let renderContext = { let renderContext = {
canvasContext: canvas.getContext('2d'), canvasContext: canvas.getContext('2d'),
viewport: viewport, viewport: viewport,
transform: [pixelRatio, 0, 0, pixelRatio, 0, 0] transform: [pixelRatio, 0, 0, pixelRatio, 0, 0]
} }
await page.render(renderContext).promise // 一页一页的渲染 await page.render(renderContext).promise // 一页一页的渲染
} }
setLoadingMessage && setLoadingMessage &&
setLoadingMessage(`渲染PDF完成`, { setLoadingMessage(`渲染PDF完成`, {
type: 'success', type: 'success',
timeout: 3456 timeout: 3456
}) })
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.miao-container { .miao-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
background-color: rgb(201, 201, 201); background-color: rgb(201, 201, 201);
overflow: hidden; overflow: hidden;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
.miao-container-topBar { .miao-container-topBar {
box-sizing: border-box; box-sizing: border-box;
padding: 0 30px; padding: 0 30px;
height: 30px; height: 30px;
width: 100%; width: 100%;
background-color: rgb(170, 176, 182); background-color: rgb(170, 176, 182);
display: flex; display: flex;
justify-content: space-around; justify-content: space-around;
align-items: center; align-items: center;
&-btn { &-btn {
cursor: pointer; cursor: pointer;
user-select: none; user-select: none;
height: 80%; height: 80%;
padding: 0 5px; padding: 0 5px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
font-size: larger; font-size: larger;
letter-spacing: 1px; letter-spacing: 1px;
color: black; color: black;
border-radius: 5px; border-radius: 5px;
&:hover { &:hover {
background-color: #eaeaea42; background-color: #eaeaea42;
} }
} }
} }
.miao-container-pdf { .miao-container-pdf {
min-width: 0; min-width: 0;
width: 100%; width: 100%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
.miao-container-pdf-content { .miao-container-pdf-content {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
} }
.miao-container-loading { .miao-container-loading {
position: absolute; position: absolute;
top: 40px; top: 40px;
background-color: aliceblue; background-color: aliceblue;
border: 1px solid black; border: 1px solid black;
height: 40px; height: 40px;
width: 200px; width: 200px;
border-radius: 10px; border-radius: 10px;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
font-size: 15px; font-size: 15px;
letter-spacing: 5px; letter-spacing: 5px;
user-select: none; user-select: none;
} }
} }
</style> </style>
+15 -16
View File
@@ -2,25 +2,24 @@
import { registerComponentOption } from '@/class/PluginCenter' import { registerComponentOption } from '@/class/PluginCenter'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: 'yourPluginKey', key: 'yourPluginKey',
name: 'yourPluginName', name: 'yourPluginName',
// icon: LogoChrome, // icon: LogoChrome,
getComponent: async () => null, getComponent: async () => null,
// (await import('yourPluginPath')).default, // (await import('yourPluginPath')).default,
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vDirs.length !== 0) { if (vDirs.length !== 0) {
return false return false
} }
if (vFiles.length !== 1) { if (vFiles.length !== 1) {
return false return false
} }
return vFiles[0].name.endsWith('?') return vFiles[0].name.endsWith('?')
}, },
disable: true disable: true
} }
export default pluginConfig export default pluginConfig
import { PluginExportType } from '@/types/type' import { PluginExportType } from '@/types/type'
export const type = PluginExportType.component export const type = PluginExportType.component
+3 -4
View File
@@ -1,5 +1,5 @@
<template> <template>
<div class="template-container"></div> <div class="template-container"></div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -8,12 +8,11 @@
// const currentFiles = defineModel<VirtualFile[]>('currentFiles', { // const currentFiles = defineModel<VirtualFile[]>('currentFiles', {
// required: true // required: true
// }) // })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.template-container { .template-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
} }
</style> </style>
+21 -22
View File
@@ -2,32 +2,31 @@ import { registerComponentOption } from '@/class/PluginCenter'
import PlayCircle from '@vicons/ionicons5/es/PlayCircle' import PlayCircle from '@vicons/ionicons5/es/PlayCircle'
const pluginConfig: registerComponentOption = { const pluginConfig: registerComponentOption = {
key: 'miaoVideoPlayer', key: 'miaoVideoPlayer',
name: '视频', name: '视频',
icon: PlayCircle, icon: PlayCircle,
getComponent: async () => getComponent: async () =>
(await import('@/plugins/miaoVideoPlayer/miaoVideoPlayer.vue')).default, (await import('@/plugins/miaoVideoPlayer/miaoVideoPlayer.vue')).default,
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vDirs.length !== 0) { if (vDirs.length !== 0) {
return false return false
} }
if (vFiles.length === 0) { if (vFiles.length === 0) {
return false return false
} }
for (let i of vFiles) { for (let i of vFiles) {
for (let s of ['mp4', 'mkv']) { for (let s of ['mp4', 'mkv']) {
if (i.name.endsWith(s)) { if (i.name.endsWith(s)) {
return true return true
}
} }
} }
return false }
}, return false
priority: 6 },
priority: 6
} }
export default pluginConfig export default pluginConfig
import { PluginExportType } from '@/types/type' import { PluginExportType } from '@/types/type'
export const type = PluginExportType.component export const type = PluginExportType.component
+274 -274
View File
@@ -1,9 +1,12 @@
<template> <template>
<miao-drop-handler @on-virtual-files="handleDropVFiles"> <miao-drop-handler @on-virtual-files="handleDropVFiles">
<div class="player-container"> <div class="player-container">
<div ref="xgPlayer" id="xgplayer"></div> <div
</div> ref="xgPlayer"
</miao-drop-handler> id="xgplayer"
></div>
</div>
</miao-drop-handler>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
@@ -20,337 +23,334 @@ import lockScreen from './playerPlugin/lockScreen/lockScreen'
import xgplayerVueApp from './src/XGPlayerVuePluginRoot.vue' import xgplayerVueApp from './src/XGPlayerVuePluginRoot.vue'
import useXGPlayerVueFrame from './playerPlugin/xgplayer-vue-frame/xgplayer-vue-frame' import useXGPlayerVueFrame from './playerPlugin/xgplayer-vue-frame/xgplayer-vue-frame'
const currentFiles = defineModel<VirtualFile[]>('currentFiles', { const currentFiles = defineModel<VirtualFile[]>('currentFiles', {
required: true required: true
}) })
const xgPlayer = ref() const xgPlayer = ref()
let _player: XGPlayer let _player: XGPlayer
const { setVideo } = (() => { const { setVideo } = (() => {
const initPlayer = (videos: VirtualFile[], texttrack: { const initPlayer = (
list: { videos: VirtualFile[],
id: number; url: string texttrack: {
list: {
id: number
url: string
text: string text: string
}[] }[]
}) => { }
const videoVFile = videos.shift() as VirtualFile ) => {
_player && _player.destroy() const videoVFile = videos.shift() as VirtualFile
_player = new XGPlayer({ _player && _player.destroy()
plugins: [ _player = new XGPlayer({
TextTrack, plugins: [TextTrack, lockScreen, useXGPlayerVueFrame(xgplayerVueApp)],
lockScreen, el: xgPlayer.value,
useXGPlayerVueFrame(xgplayerVueApp), url: videoVFile.url,
], width: '100%',
el: xgPlayer.value, height: '100%',
url: videoVFile.url, volume: 1,
width: '100%', // loop: true,
height: '100%', // pip: true,
volume: 1, videoFillMode: 'contain',
// loop: true, autoplay: true,
// pip: true, download: true,
videoFillMode: 'contain', ignores: [videos.length === 0 ? 'playNext' : undefined].filter(
autoplay: true, (v) => v
download: true, ) as string[],
ignores: [videos.length === 0 ? 'playNext' : undefined].filter(v => v) as string[], lang: 'zh-cn',
lang: 'zh-cn', playbackRate: [0.1, 0.3, 0.5, 0.75, 1, 1.5, 2, 3, 5, 10],
playbackRate: [0.1, 0.3, 0.5, 0.75, 1, 1.5, 2, 3, 5, 10], texttrack,
texttrack, screenShot: {
screenShot: { saveImg: true,
saveImg: true, quality: 1,
quality: 1, type: 'image/png',
type: 'image/png', format: '.png'
format: '.png' },
}, playNext: {
playNext: { urlList: videos.map((v) => v.url)
urlList: videos.map(v => v.url) },
}, progress: {
progress: { isDragingSeek: true
isDragingSeek: true }
}, // mobile: {
// mobile: { // disableGesture: true
// disableGesture: true // }
// } })
}) }
} return {
return { setVideo: async (
setVideo: async ( videoVFiles: VirtualFile[],
videoVFiles: VirtualFile[], textTrackFiles?: VirtualFile[]
textTrackFiles?: VirtualFile[] ) => {
) => { // 天哪什么精神状态会写出这种代码
// 天哪什么精神状态会写出这种代码 textTrackFiles &&
textTrackFiles && textTrackFiles.push(...findTextTrack(currentFiles.value))
textTrackFiles.push(...findTextTrack(currentFiles.value)) textTrackFiles = uniq(textTrackFiles)
textTrackFiles = uniq(textTrackFiles) currentFiles.value = uniq([
currentFiles.value = uniq([...currentFiles.value, ...videoVFiles, ...(textTrackFiles ?? [])]) ...currentFiles.value,
const videos = findVideo(uniq([...currentFiles.value, ...videoVFiles])) ...videoVFiles,
const _list = [] ...(textTrackFiles ?? [])
if (textTrackFiles) { ])
for (let i of textTrackFiles) { const videos = findVideo(uniq([...currentFiles.value, ...videoVFiles]))
if (i.name.endsWith('srt')) { const _list = []
const response = await axios.get(i.url) if (textTrackFiles) {
// console.log(srtToVtt(response.data)) for (let i of textTrackFiles) {
const url = setUrl(new Blob([srtToVtt(response.data)])) if (i.name.endsWith('srt')) {
_list.push({ const response = await axios.get(i.url)
id: i.id, // console.log(srtToVtt(response.data))
url, const url = setUrl(new Blob([srtToVtt(response.data)]))
// 这个language会覆盖id的设置,导致无法切换字幕 _list.push({
// language: 'zh-cn', id: i.id,
text: i.name url,
}) // 这个language会覆盖id的设置,导致无法切换字幕
} else if (i.name.endsWith('ass')) { // language: 'zh-cn',
const response = await axios.get(i.url) text: i.name
// console.log(assToVtt(response.data)) })
const url = setUrl(new Blob([assToVtt(response.data)])) } else if (i.name.endsWith('ass')) {
_list.push({ const response = await axios.get(i.url)
id: i.id, // console.log(assToVtt(response.data))
url, const url = setUrl(new Blob([assToVtt(response.data)]))
text: i.name _list.push({
}) id: i.id,
} else if (i.name.endsWith('ssa')) { url,
const response = await axios.get(i.url) text: i.name
// console.log(ssaToVtt(response.data)) })
const url = setUrl(new Blob([ssaToVtt(response.data)])) } else if (i.name.endsWith('ssa')) {
_list.push({ const response = await axios.get(i.url)
id: i.id, // console.log(ssaToVtt(response.data))
url, const url = setUrl(new Blob([ssaToVtt(response.data)]))
text: i.name _list.push({
}) id: i.id,
} else { url,
_list.push({ text: i.name
id: i.id, })
url: i.url, } else {
text: i.name _list.push({
}) id: i.id,
} url: i.url,
} text: i.name
})
}
} }
const texttrack = { }
list: _list const texttrack = {
} list: _list
initPlayer([...videos], texttrack) }
} initPlayer([...videos], texttrack)
} }
}
})() })()
const { setUrl, destroyUrl } = (() => { const { setUrl, destroyUrl } = (() => {
const urlList: string[] = [] const urlList: string[] = []
return { return {
setUrl(blob: Blob) { setUrl(blob: Blob) {
const url = URL.createObjectURL(blob) const url = URL.createObjectURL(blob)
urlList.push(url) urlList.push(url)
return url return url
}, },
destroyUrl() { destroyUrl() {
for (const url of urlList) { for (const url of urlList) {
URL.revokeObjectURL(url) URL.revokeObjectURL(url)
} }
} }
} }
})() })()
const handleDropVFiles = (files: VirtualFile[]) => { const handleDropVFiles = (files: VirtualFile[]) => {
setVideo(findVideo(files.reverse()), findTextTrack(files)) setVideo(findVideo(files.reverse()), findTextTrack(files))
} }
function srtToVtt(srt: string) { function srtToVtt(srt: string) {
// 将 SRT 字幕按行分割 // 将 SRT 字幕按行分割
const lines = srt.split('\n') const lines = srt.split('\n')
let vtt = 'WEBVTT\n\n' // VTT 文件的开头 let vtt = 'WEBVTT\n\n' // VTT 文件的开头
let index = 0 let index = 0
while (index < lines.length) { while (index < lines.length) {
// 跳过空行 // 跳过空行
if (lines[index].trim() === '') { if (lines[index].trim() === '') {
index++ index++
continue continue
} }
// SRT 中的序号 // SRT 中的序号
lines[index].trim() lines[index].trim()
index++ index++
// 时间戳 // 时间戳
const timeLine = lines[index].trim().replace(/,/g, '.') // 将逗号替换为点 const timeLine = lines[index].trim().replace(/,/g, '.') // 将逗号替换为点
index++ index++
// 字幕文本 // 字幕文本
let text = '' let text = ''
while (index < lines.length && lines[index].trim() !== '') { while (index < lines.length && lines[index].trim() !== '') {
text += lines[index].trim() + '\n' text += lines[index].trim() + '\n'
index++ index++
} }
// 添加到 VTT 字幕中 // 添加到 VTT 字幕中
vtt += `${timeLine}\n${text.trim()}\n\n` vtt += `${timeLine}\n${text.trim()}\n\n`
} }
return vtt return vtt
} }
function assToVtt(assContent: string) { function assToVtt(assContent: string) {
// 分割 ASS 内容为行 // 分割 ASS 内容为行
const lines = assContent.split('\n') const lines = assContent.split('\n')
let vttContent = 'WEBVTT\n\n' // VTT 文件头 let vttContent = 'WEBVTT\n\n' // VTT 文件头
// 遍历每一行,寻找字幕条目 // 遍历每一行,寻找字幕条目
for (let line of lines) { for (let line of lines) {
// 只处理 [Events] 部分后的 Dialogue 行 // 只处理 [Events] 部分后的 Dialogue 行
if (line.startsWith('Dialogue:')) { if (line.startsWith('Dialogue:')) {
// 提取时间戳和文本 // 提取时间戳和文本
const parts = line.split(',') const parts = line.split(',')
if (parts.length >= 5) { if (parts.length >= 5) {
// 将时间戳格式化为 VTT 格式 // 将时间戳格式化为 VTT 格式
const startTime = parts[1] const startTime = parts[1]
.trim() .trim()
.replace('.', ',') .replace('.', ',')
.replace(',', '.') // 替换 . 为 ,,然后再替换为 . .replace(',', '.') // 替换 . 为 ,,然后再替换为 .
const endTime = parts[2] const endTime = parts[2].trim().replace('.', ',').replace(',', '.') // 替换 . 为 ,,然后再替换为 .
.trim()
.replace('.', ',')
.replace(',', '.') // 替换 . 为 ,,然后再替换为 .
// 确保时间戳是两位数格式 // 确保时间戳是两位数格式
const formattedStartTime = startTime.replace( const formattedStartTime = startTime.replace(
/(\d+):(\d+):(\d+)\.(\d+)/, /(\d+):(\d+):(\d+)\.(\d+)/,
(match: any, h: any, m: any, s: any, ms: any) => { (match: any, h: any, m: any, s: any, ms: any) => {
match match
return `${String(h).padStart(2, '0')}:${String( return `${String(h).padStart(2, '0')}:${String(m).padStart(
m 2,
).padStart(2, '0')}:${String(s).padStart( '0'
2, )}:${String(s).padStart(2, '0')}.${String(ms).padStart(3, '0')}`
'0' }
)}.${String(ms).padStart(3, '0')}` )
}
)
const formattedEndTime = endTime.replace( const formattedEndTime = endTime.replace(
/(\d+):(\d+):(\d+)\.(\d+)/, /(\d+):(\d+):(\d+)\.(\d+)/,
(match: any, h: any, m: any, s: any, ms: any) => { (match: any, h: any, m: any, s: any, ms: any) => {
match match
return `${String(h).padStart(2, '0')}:${String( return `${String(h).padStart(2, '0')}:${String(m).padStart(
m 2,
).padStart(2, '0')}:${String(s).padStart( '0'
2, )}:${String(s).padStart(2, '0')}.${String(ms).padStart(3, '0')}`
'0' }
)}.${String(ms).padStart(3, '0')}` )
}
)
const rawText = parts.slice(9).join(',').trim() // 提取文本 const rawText = parts.slice(9).join(',').trim() // 提取文本
// 清理文本中的样式信息 // 清理文本中的样式信息
const cleanText = rawText const cleanText = rawText
.replace(/{[^}]*}/g, '') .replace(/{[^}]*}/g, '')
.replace(/\\N/g, '\n') .replace(/\\N/g, '\n')
.trim() .trim()
// 添加到 VTT 内容 // 添加到 VTT 内容
vttContent += `${formattedStartTime} --> ${formattedEndTime}\n${cleanText}\n\n` vttContent += `${formattedStartTime} --> ${formattedEndTime}\n${cleanText}\n\n`
} }
} }
} }
return vttContent.trim() // 返回 VTT 内容,去掉末尾空行 return vttContent.trim() // 返回 VTT 内容,去掉末尾空行
} }
function ssaToVtt(ssaContent: string): string { function ssaToVtt(ssaContent: string): string {
function convertSsaTimeToVtt(ssaTime: string): string { function convertSsaTimeToVtt(ssaTime: string): string {
const timeParts = ssaTime.split(':') const timeParts = ssaTime.split(':')
const hours = timeParts[0].padStart(2, '0') const hours = timeParts[0].padStart(2, '0')
const minutes = timeParts[1].padStart(2, '0') const minutes = timeParts[1].padStart(2, '0')
const secondsAndMilliseconds = timeParts[2].split('.') const secondsAndMilliseconds = timeParts[2].split('.')
const seconds = secondsAndMilliseconds[0].padStart(2, '0') const seconds = secondsAndMilliseconds[0].padStart(2, '0')
const milliseconds = (secondsAndMilliseconds[1] || '0').padEnd(3, '0') const milliseconds = (secondsAndMilliseconds[1] || '0').padEnd(3, '0')
return `${hours}:${minutes}:${seconds}.${milliseconds}` return `${hours}:${minutes}:${seconds}.${milliseconds}`
} }
const lines = ssaContent.split('\n') const lines = ssaContent.split('\n')
let vttContent = 'WEBVTT\n\n' // VTT文件头 let vttContent = 'WEBVTT\n\n' // VTT文件头
let inEvents = false let inEvents = false
for (const line of lines) { for (const line of lines) {
// 检查是否进入[Events]部分 // 检查是否进入[Events]部分
if (line.startsWith('[Events]')) { if (line.startsWith('[Events]')) {
inEvents = true inEvents = true
continue continue
} }
// 如果在[Events]部分,处理对话行 // 如果在[Events]部分,处理对话行
if (inEvents && line.startsWith('Dialogue:')) { if (inEvents && line.startsWith('Dialogue:')) {
const parts = line.split(',') const parts = line.split(',')
if (parts.length >= 3) { if (parts.length >= 3) {
const startTime = convertSsaTimeToVtt(parts[1].trim()) const startTime = convertSsaTimeToVtt(parts[1].trim())
const endTime = convertSsaTimeToVtt(parts[2].trim()) const endTime = convertSsaTimeToVtt(parts[2].trim())
const text = parts.slice(9).join(',').trim() // 获取字幕文本 const text = parts.slice(9).join(',').trim() // 获取字幕文本
// 去除样式标签 // 去除样式标签
const cleanText = text.replace(/{[^}]*}/g, '').trim() const cleanText = text.replace(/{[^}]*}/g, '').trim()
// 添加到VTT内容 // 添加到VTT内容
vttContent += `${startTime} --> ${endTime}\n${cleanText}\n\n` vttContent += `${startTime} --> ${endTime}\n${cleanText}\n\n`
} }
} }
} }
return vttContent return vttContent
} }
const findVideo = (vFiles: VirtualFile[]) => const findVideo = (vFiles: VirtualFile[]) =>
uniq(vFiles.filter((v) => { uniq(
for (let s of ['mp4', 'mp3', 'mkv']) { vFiles.filter((v) => {
for (let s of ['mp4', 'mp3', 'mkv']) {
if (v.name.endsWith(s)) { if (v.name.endsWith(s)) {
return true return true
} }
} }
return false return false
})) })
)
const findTextTrack = (vFiles: VirtualFile[]) => const findTextTrack = (vFiles: VirtualFile[]) =>
vFiles.filter((v) => { vFiles.filter((v) => {
for (let s of ['vtt', 'srt', 'ass', 'ssa']) { for (let s of ['vtt', 'srt', 'ass', 'ssa']) {
if (v.name.endsWith(s)) { if (v.name.endsWith(s)) {
return true return true
} }
} }
return false return false
}) })
onMounted(() => { onMounted(() => {
if (currentFiles.value.length) { if (currentFiles.value.length) {
currentFiles.value.reverse() currentFiles.value.reverse()
setVideo( setVideo(findVideo(currentFiles.value), findTextTrack(currentFiles.value))
findVideo(currentFiles.value), }
findTextTrack(currentFiles.value)
)
}
}) })
onBeforeUnmount(() => { onBeforeUnmount(() => {
_player.destroy() _player.destroy()
destroyUrl() destroyUrl()
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.player-container { .player-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
position: relative; position: relative;
background-color: grey; background-color: grey;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
#xgplayer { #xgplayer {
width: 100%; width: 100%;
// height: 500px; // height: 500px;
background-color: black; background-color: black;
} }
} }
.video-js { .video-js {
width: 100%; width: 100%;
background-color: rgb(0, 0, 0); background-color: rgb(0, 0, 0);
} }
</style> </style>
@@ -1,51 +1,55 @@
.lock-div { .lock-div {
position: absolute; position: absolute;
z-index: 20; z-index: 20;
left: 15px; left: 15px;
top: 50%; top: 50%;
transform: translateY(-50%); transform: translateY(-50%);
width: 30px; width: 30px;
aspect-ratio: 1; aspect-ratio: 1;
cursor: pointer; cursor: pointer;
color: #f2f2f2; color: #f2f2f2;
opacity: 1; opacity: 1;
visibility: visible; visibility: visible;
transition: opacity 0.5s ease, visibility 0.5s ease, width 0.25s ease, left 0.25s ease; transition:
pointer-events: all !important; opacity 0.5s ease,
svg { visibility 0.5s ease,
width: inherit; width 0.25s ease,
height: inherit; left 0.25s ease;
} pointer-events: all !important;
&:hover { svg {
width: 36px; width: inherit;
left: 12px; height: inherit;
} }
&:hover {
width: 36px;
left: 12px;
}
} }
.xgplayer.xgplayer-inactive .lock-div { .xgplayer.xgplayer-inactive .lock-div {
pointer-events: none; pointer-events: none;
cursor: default; cursor: default;
visibility: hidden; visibility: hidden;
opacity: 0; opacity: 0;
} }
.overlay-div { .overlay-div {
position: absolute; position: absolute;
z-index: 10; z-index: 10;
top: 0; top: 0;
left: 0; left: 0;
width: 100%; width: 100%;
height: 100%; height: 100%;
background-color: rgba(0, 0, 0, 0); background-color: rgba(0, 0, 0, 0);
display: none; display: none;
cursor: auto; cursor: auto;
} }
.xgplayer.xgplayer-inactive .overlay-div { .xgplayer.xgplayer-inactive .overlay-div {
pointer-events: none; pointer-events: none;
cursor: none; cursor: none;
} }
.xgplayer .xgplayer-locked { .xgplayer .xgplayer-locked {
pointer-events: none; pointer-events: none;
} }
@@ -1,104 +1,125 @@
import { BasePlugin } from "xgplayer"; import { BasePlugin } from 'xgplayer'
import "./lockScreen.scss"; import './lockScreen.scss'
import MobilePlugin from "xgplayer/es/plugins/mobile"; import MobilePlugin from 'xgplayer/es/plugins/mobile'
export default class LockPlugin extends BasePlugin { export default class LockPlugin extends BasePlugin {
static get pluginName() { static get pluginName() {
return "lockPlugin"; return 'lockPlugin'
} }
private locked: boolean; private locked: boolean
private lockDiv: HTMLDivElement = document.createElement("div"); private lockDiv: HTMLDivElement = document.createElement('div')
private overlayDiv: HTMLDivElement = document.createElement("div"); private overlayDiv: HTMLDivElement = document.createElement('div')
private lockOpenSVG: string = ` private lockOpenSVG: string = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path d="M336 208v-95a80 80 0 0 0-160 0v95" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"></path> <path d="M336 208v-95a80 80 0 0 0-160 0v95" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"></path>
<rect x="96" y="208" width="320" height="272" rx="48" ry="48" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"></rect> <rect x="96" y="208" width="320" height="272" rx="48" ry="48" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"></rect>
</svg>`; </svg>`
private lockClosedSVG: string = ` private lockClosedSVG: string = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path d="M336 112a80 80 0 0 0-160 0v96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"></path> <path d="M336 112a80 80 0 0 0-160 0v96" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"></path>
<rect x="96" y="208" width="320" height="272" rx="48" ry="48" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"></rect> <rect x="96" y="208" width="320" height="272" rx="48" ry="48" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"></rect>
</svg>`; </svg>`
constructor(args: any) { constructor(args: any) {
super(args); super(args)
this.locked = false; this.locked = false
} }
afterCreate() { afterCreate() {
this.initLockDiv(); this.initLockDiv()
this.initOverlayDiv(); this.initOverlayDiv()
this.bindEvents(); this.bindEvents()
} }
private initLockDiv() { private initLockDiv() {
this.lockDiv.innerHTML = this.lockClosedSVG; this.lockDiv.innerHTML = this.lockClosedSVG
this.lockDiv.className = "lock-div"; this.lockDiv.className = 'lock-div'
this.player.root !== null && this.player.root.appendChild(this.lockDiv); this.player.root !== null && this.player.root.appendChild(this.lockDiv)
} }
private initOverlayDiv() { private initOverlayDiv() {
this.overlayDiv.className = "overlay-div"; this.overlayDiv.className = 'overlay-div'
this.player.root !== null && this.player.root.appendChild(this.overlayDiv); this.player.root !== null && this.player.root.appendChild(this.overlayDiv)
this.overlayDiv.addEventListener('mousedown', (e) => { this.overlayDiv.addEventListener('mousedown', (e) => {
e.preventDefault(); e.preventDefault()
}); })
this.overlayDiv.addEventListener('mousemove', (e) => { this.overlayDiv.addEventListener('mousemove', (e) => {
e.preventDefault(); e.preventDefault()
}); })
} }
private bindEvents() { private bindEvents() {
this.lockDiv!.addEventListener("click", this.toggleLock.bind(this)); this.lockDiv!.addEventListener('click', this.toggleLock.bind(this))
this.player.root !== null && this.player.root.addEventListener("click", this.preventClick.bind(this), true); this.player.root !== null &&
this.player.usePluginHooks("progress", "dragstart", () => { this.player.root.addEventListener(
if (this.locked) { 'click',
return false; this.preventClick.bind(this),
} true
return true; )
}); this.player.usePluginHooks('progress', 'dragstart', () => {
// 阻止进度条默认行为 if (this.locked) {
for(const event of ['dragstart', 'drag', 'dragend']) { return false
this.player.usePluginHooks("progress", event, () => { }
if (this.locked) { return true
return false; })
} // 阻止进度条默认行为
return true; for (const event of ['dragstart', 'drag', 'dragend']) {
}); this.player.usePluginHooks('progress', event, () => {
} if (this.locked) {
} return false
}
return true
})
}
}
private toggleLock() { private toggleLock() {
const mobile = this.getPlugin('mobile') as MobilePlugin | undefined const mobile = this.getPlugin('mobile') as MobilePlugin | undefined
// mobile?.disableGesture() // mobile?.disableGesture()
if (this.lockDiv && this.overlayDiv) { if (this.lockDiv && this.overlayDiv) {
this.locked = !this.locked; this.locked = !this.locked
this.lockDiv.innerHTML = this.locked ? this.lockOpenSVG : this.lockClosedSVG; this.lockDiv.innerHTML = this.locked
this.overlayDiv.style.display = this.locked ? "block" : "none"; ? this.lockOpenSVG
this.player.controls && (this.locked ? this.player.controls.hide() : this.player.controls.show()); : this.lockClosedSVG
this.player.root !== null && this.player.root.classList.toggle("xgplayer-locked", this.locked); this.overlayDiv.style.display = this.locked ? 'block' : 'none'
this.locked ? mobile?.disableGesture() : mobile?.enableGesture() this.player.controls &&
} (this.locked
} ? this.player.controls.hide()
: this.player.controls.show())
this.player.root !== null &&
this.player.root.classList.toggle('xgplayer-locked', this.locked)
this.locked ? mobile?.disableGesture() : mobile?.enableGesture()
}
}
private preventClick(event: MouseEvent) { private preventClick(event: MouseEvent) {
if (this.locked && event.target instanceof HTMLElement && !event.target.classList.contains("lock-div")) { if (
event.stopPropagation(); this.locked &&
event.preventDefault(); event.target instanceof HTMLElement &&
} !event.target.classList.contains('lock-div')
} ) {
event.stopPropagation()
event.preventDefault()
}
}
destroy() { destroy() {
if (this.lockDiv) { if (this.lockDiv) {
this.lockDiv.removeEventListener("click", this.toggleLock.bind(this)); this.lockDiv.removeEventListener('click', this.toggleLock.bind(this))
this.player.root !== null && this.player.root.removeEventListener("click", this.preventClick.bind(this), true); this.player.root !== null &&
this.player.root !== null && this.player.root.removeChild(this.lockDiv); this.player.root.removeEventListener(
} 'click',
if (this.overlayDiv) { this.preventClick.bind(this),
this.player.root !== null && this.player.root.removeChild(this.overlayDiv); true
} )
} this.player.root !== null && this.player.root.removeChild(this.lockDiv)
}
if (this.overlayDiv) {
this.player.root !== null &&
this.player.root.removeChild(this.overlayDiv)
}
}
} }
@@ -1,36 +1,35 @@
<template> <template>
<Teleport :to="player.root"> <Teleport :to="player.root">
<App v-bind="pick(toRaw(props), ['player', 'root'])"></App> <App v-bind="pick(toRaw(props), ['player', 'root'])"></App>
</Teleport> </Teleport>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { Component, toRaw } from "vue"; import { Component, toRaw } from 'vue'
import Player from "xgplayer/es/player"; import Player from 'xgplayer/es/player'
import pick from "lodash/pick"; import pick from 'lodash/pick'
const props = defineProps({ const props = defineProps({
player: { player: {
type: Player, type: Player,
required: true required: true
}, },
root: { root: {
type: Element, type: Element,
required: true required: true
}, },
App: { App: {
type: Object as () => Component, type: Object as () => Component,
required: true required: true
} }
}) })
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.test { .test {
width: 50px; width: 50px;
height: 50px; height: 50px;
background-color: aliceblue; background-color: aliceblue;
position: absolute; position: absolute;
right: 0; right: 0;
} }
</style> </style>
@@ -1,35 +1,39 @@
import { App, Component, createApp } from "vue"; import { App, Component, createApp } from 'vue'
import { BasePlugin } from "xgplayer"; import { BasePlugin } from 'xgplayer'
import fakeApp from "./fakeRoot.vue"; import fakeApp from './fakeRoot.vue'
const useXGPlayerVueFrame = (App: Component) => { const useXGPlayerVueFrame = (App: Component) => {
return class XGPlayerVueFrame extends BasePlugin { return class XGPlayerVueFrame extends BasePlugin {
static get pluginName() { static get pluginName() {
return "xgplayerVueFrame"; return 'xgplayerVueFrame'
} }
private root: HTMLDivElement | null = null; private root: HTMLDivElement | null = null
private app: App<Element> | null = null; private app: App<Element> | null = null
constructor(args: any) { constructor(args: any) {
super(args); super(args)
} }
afterCreate() { afterCreate() {
this.createVueFrame(); this.createVueFrame()
} }
private createVueFrame() { private createVueFrame() {
this.root = document.createElement("div"); this.root = document.createElement('div')
this.app = createApp(fakeApp, { player: this.player, root: this.root, App }) this.app = createApp(fakeApp, {
this.app.mount(this.root); player: this.player,
// this.app.mount(this.player.root); root: this.root,
} App
})
this.app.mount(this.root)
// this.app.mount(this.player.root);
}
destroy() { destroy() {
this.app?.unmount() this.app?.unmount()
} }
}; }
}; }
export default useXGPlayerVueFrame; export default useXGPlayerVueFrame
@@ -1,33 +1,32 @@
<template> <template>
<!-- <div class="test"></div> --> <!-- <div class="test"></div> -->
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from "vue"; import { onMounted } from 'vue'
import Player from "xgplayer/es/player"; import Player from 'xgplayer/es/player'
const props = defineProps({ const props = defineProps({
player: { player: {
type: Player, type: Player,
required: true required: true
}, },
root: { root: {
type: Element, type: Element,
required: true required: true
} }
}) })
onMounted(() => { onMounted(() => {
props props
}) })
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.test { .test {
width: 50px; width: 50px;
height: 50px; height: 50px;
background-color: aliceblue; background-color: aliceblue;
position: absolute; position: absolute;
right: 0; right: 0;
} }
</style> </style>
File diff suppressed because it is too large. Load diff
@@ -1,36 +1,35 @@
import type { Plugin, registerComponentOption } from "@/class/PluginCenter"; import type { Plugin, registerComponentOption } from '@/class/PluginCenter'
export function checkNormalPlugin(obj: any): obj is Plugin { export function checkNormalPlugin(obj: any): obj is Plugin {
return ( return (
typeof obj === "object" && typeof obj === 'object' &&
obj!== null && obj !== null &&
typeof obj.name === "string" && typeof obj.name === 'string' &&
(obj.icon === undefined || typeof obj.icon === "object") && (obj.icon === undefined || typeof obj.icon === 'object') &&
typeof obj.disable === "boolean" && typeof obj.disable === 'boolean' &&
Array.isArray(obj.group) && Array.isArray(obj.group) &&
obj.group.every((group: any) => typeof group === "string") && obj.group.every((group: any) => typeof group === 'string') &&
typeof obj.priority === "number" && typeof obj.priority === 'number' &&
typeof obj.filter === "function" && typeof obj.filter === 'function' &&
typeof obj.func === "function" typeof obj.func === 'function'
); )
} }
export function checkComponentPlugin(obj: any): obj is registerComponentOption {
export function checkComponentPlugin( return (
obj: any typeof obj === 'object' &&
): obj is registerComponentOption { obj !== null &&
return ( typeof obj.key === 'string' &&
typeof obj === "object" && typeof obj.name === 'string' &&
obj!== null && (obj.icon === undefined || typeof obj.icon === 'object') &&
typeof obj.key === "string" && typeof obj.getComponent === 'function' &&
typeof obj.name === "string" && (obj.group === undefined ||
(obj.icon === undefined || typeof obj.icon === "object") && (Array.isArray(obj.group) &&
typeof obj.getComponent === "function" && obj.group.every((item: any) => typeof item === 'string'))) &&
((obj.group === undefined) || (Array.isArray(obj.group) && obj.group.every((item: any) => typeof item === "string"))) && typeof obj.filter === 'function' &&
typeof obj.filter === "function" && (obj.disable === undefined || typeof obj.disable === 'boolean') &&
(obj.disable === undefined || typeof obj.disable === "boolean") && (obj.exitConfirm === undefined || typeof obj.exitConfirm === 'boolean') &&
(obj.exitConfirm === undefined || typeof obj.exitConfirm === "boolean") && (obj.single === undefined || typeof obj.single === 'boolean') &&
(obj.single === undefined || typeof obj.single === "boolean") && (obj.priority === undefined || typeof obj.priority === 'number')
(obj.priority === undefined || typeof obj.priority === "number") )
);
} }
+24 -24
View File
@@ -1,29 +1,29 @@
import { Plugin, PluginGroup } from "@/class/PluginCenter"; import { Plugin, PluginGroup } from '@/class/PluginCenter'
import { LogoGithub } from "@vicons/ionicons5"; import { LogoGithub } from '@vicons/ionicons5'
import { PluginExportType } from "@/types/type"; import { PluginExportType } from '@/types/type'
import { shallowRef } from "vue"; import { shallowRef } from 'vue'
import registerExternalPlugin from "./registerExternalPlugin"; import registerExternalPlugin from './registerExternalPlugin'
const pluginConfig: Plugin = { const pluginConfig: Plugin = {
name: "导入插件", name: '导入插件',
icon: shallowRef(LogoGithub), icon: shallowRef(LogoGithub),
filter: (vDirs, vFiles) => { filter: (vDirs, vFiles) => {
if (vDirs.length !== 0) { if (vDirs.length !== 0) {
return false; return false
} }
if (vFiles.length !== 1) { if (vFiles.length !== 1) {
return false; return false
} }
return vFiles[0].name.endsWith('js') return vFiles[0].name.endsWith('js')
}, },
disable: false, disable: false,
group: [PluginGroup.default], group: [PluginGroup.default],
func: registerExternalPlugin, func: registerExternalPlugin,
priority: -1 priority: -1
}; }
export default pluginConfig; export default pluginConfig
export const type = PluginExportType.default; export const type = PluginExportType.default
export const key = 'registerExternalPlugin'; export const key = 'registerExternalPlugin'
@@ -1,36 +1,42 @@
import VirtualDirectory, { VirtualFile } from "@/class/VirtualDirectory"; import VirtualDirectory, { VirtualFile } from '@/class/VirtualDirectory'
// import useMiaoFetchApi from "@/hooks/useMiaoFetchApi"; // import useMiaoFetchApi from "@/hooks/useMiaoFetchApi";
import { PluginExportType, usePluginHooksType } from "@/types/type"; import { PluginExportType, usePluginHooksType } from '@/types/type'
import type { Plugin, registerComponentOption } from "@/class/PluginCenter"; import type { Plugin, registerComponentOption } from '@/class/PluginCenter'
import { checkComponentPlugin, checkNormalPlugin } from "./checkPluginAvailable"; import { checkComponentPlugin, checkNormalPlugin } from './checkPluginAvailable'
// const miaoFetchApi = useMiaoFetchApi() // const miaoFetchApi = useMiaoFetchApi()
export default async function registerExternalPlugin(_VDirectories: VirtualDirectory[], VFiles: VirtualFile[], hooks: usePluginHooksType) { export default async function registerExternalPlugin(
try { _VDirectories: VirtualDirectory[],
const targetPluginVFile = VFiles[0] as VirtualFile VFiles: VirtualFile[],
const plugin = await import(/* @vite-ignore */ targetPluginVFile.url) as { hooks: usePluginHooksType
default: registerComponentOption | Plugin; ) {
type: PluginExportType; try {
key?: string; const targetPluginVFile = VFiles[0] as VirtualFile
} const plugin = (await import(
const pc = hooks.getPluginCenter() /* @vite-ignore */ targetPluginVFile.url
if (plugin.type === PluginExportType.default) { )) as {
if (checkNormalPlugin(plugin.default) === false) { default: registerComponentOption | Plugin
throw('插件不合法') type: PluginExportType
} key?: string
pc.register(plugin.key ?? `${Math.random()}`, plugin.default as Plugin) }
} else { const pc = hooks.getPluginCenter()
if (checkComponentPlugin(plugin.default) === false) { if (plugin.type === PluginExportType.default) {
throw('插件不合法') if (checkNormalPlugin(plugin.default) === false) {
} throw '插件不合法'
pc.registerComponent(plugin.default as registerComponentOption) }
} pc.register(plugin.key ?? `${Math.random()}`, plugin.default as Plugin)
} catch (e) { } else {
console.error(e); if (checkComponentPlugin(plugin.default) === false) {
hooks.globalAlertTip('导入外部插件失败', { throw '插件不合法'
type: 'error', }
timeout: 3000 pc.registerComponent(plugin.default as registerComponentOption)
}) }
} } catch (e) {
console.error(e)
hooks.globalAlertTip('导入外部插件失败', {
type: 'error',
timeout: 3000
})
}
} }
+2 -3
View File
@@ -1,4 +1,3 @@
:root :root body {
body { background-color: aliceblue;
background-color: aliceblue;
} }
+27 -27
View File
@@ -1,39 +1,39 @@
import { AxiosRequestConfig } from "axios"; import { AxiosRequestConfig } from 'axios'
import { directory, file } from "./type"; import { directory, file } from './type'
export type miaoFetchConfig = { export type miaoFetchConfig = {
retry?: number retry?: number
axiosOption?: AxiosRequestConfig<any> axiosOption?: AxiosRequestConfig<any>
} }
export type getOption = {} & miaoFetchConfig; export type getOption = {} & miaoFetchConfig
export type getFileOption = { export type getFileOption = {
/** /**
* 下载进度回调函数 * 下载进度回调函数
* @param {any} percent 进度百分比,float类型, 0-1 * @param {any} percent 进度百分比,float类型, 0-1
*/ */
onProcess?: (percent: number) => void; onProcess?: (percent: number) => void
} & miaoFetchConfig; } & miaoFetchConfig
export type getResponse = (file | directory)[]; export type getResponse = (file | directory)[]
export type uploadOption = { export type uploadOption = {
/** /**
* 上传进度回调函数 * 上传进度回调函数
* @param {any} percent 进度百分比,float类型, 0-1 * @param {any} percent 进度百分比,float类型, 0-1
*/ */
onProcess?: (percent: number) => void; onProcess?: (percent: number) => void
/** /**
* 上传文件执行的操作 * 上传文件执行的操作
* write即为覆盖写 * write即为覆盖写
* append即为增量写 * append即为增量写
*/ */
type?: "write" | "append"; type?: 'write' | 'append'
} & miaoFetchConfig; } & miaoFetchConfig
export type deleteOption = {} & miaoFetchConfig; export type deleteOption = {} & miaoFetchConfig
export type renameOption = {} & miaoFetchConfig; export type renameOption = {} & miaoFetchConfig
export type cutOption = {} & miaoFetchConfig export type cutOption = {} & miaoFetchConfig
export type mkdirOption = {} & miaoFetchConfig export type mkdirOption = {} & miaoFetchConfig
export type queryOption = {} & miaoFetchConfig; export type queryOption = {} & miaoFetchConfig
+37 -31
View File
@@ -1,48 +1,54 @@
import PluginCenter from "@/class/PluginCenter"; import PluginCenter from '@/class/PluginCenter'
import VirtualDirectory from "@/class/VirtualDirectory"; import VirtualDirectory from '@/class/VirtualDirectory'
import type { VirtualPages } from "@/class/VirtualPage"; import type { VirtualPages } from '@/class/VirtualPage'
export type stats = { export type stats = {
atimeMs: number; // 上次访问时间(毫秒) atimeMs: number // 上次访问时间(毫秒)
birthtimeMs: number; // 创建时间(毫秒) birthtimeMs: number // 创建时间(毫秒)
ctimeMs: number; // 状态更改时间(毫秒) ctimeMs: number // 状态更改时间(毫秒)
mtimeMs: number; // 上次修改时间(毫秒) mtimeMs: number // 上次修改时间(毫秒)
}; }
export type file = { export type file = {
name: string; name: string
size: number; size: number
type?: "file"; type?: 'file'
stats: stats; stats: stats
}; }
export type directory = { export type directory = {
name: string; name: string
// 考虑到可能还没请求过来 // 考虑到可能还没请求过来
content?: (file | directory)[]; content?: (file | directory)[]
type?: "directory"; type?: 'directory'
stats: stats; stats: stats
parent?: directory; parent?: directory
}; }
export type alertTipType = (content: string, options?: AlertTipMessageOptions) => (newContent: string, newOptions?: AlertTipMessageOptions) => void; export type alertTipType = (
content: string,
options?: AlertTipMessageOptions
) => (newContent: string, newOptions?: AlertTipMessageOptions) => void
export interface AlertTipMessageOptions { export interface AlertTipMessageOptions {
type?: "info" | "success" | "error"; type?: 'info' | 'success' | 'error'
timeout?: number; timeout?: number
id?: number; id?: number
} }
export enum PluginExportType { export enum PluginExportType {
default = "default", default = 'default',
component = "component" component = 'component'
} }
export interface usePluginHooksType { export interface usePluginHooksType {
globalAlertTip: alertTipType; globalAlertTip: alertTipType
getViews: () => VirtualPages; getViews: () => VirtualPages
getPluginCenter: () => PluginCenter; getPluginCenter: () => PluginCenter
getRootVDirectory: () => VirtualDirectory; getRootVDirectory: () => VirtualDirectory
} }
export type Equals<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false; export type Equals<X, Y> =
(<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2
? true
: false