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
+8114 -7395

No files matched your search

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