File size: 2,139 Bytes
b173115 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
import { FileNodeInfo, getTargetFolderFiles } from '@/api/files'
import { first } from 'lodash-es'
import { SortMethod, sortFiles } from './fileSort'
import { isMediaFile } from '@/util'
interface TreeNode {
children: TreeNode[]
info: FileNodeInfo
}
export class Walker {
root: TreeNode
execQueue: { fn: () => Promise<TreeNode>; info: FileNodeInfo }[] = []
constructor(entryPath: string, private sortMethod = SortMethod.CREATED_TIME_DESC) {
this.root = {
children: [],
info: {
name: entryPath,
size: '-',
bytes: 0,
created_time: '',
is_under_scanned_path: true,
date: '',
type: 'dir',
fullpath: entryPath
}
}
this.fetchChildren(this.root)
}
reset () {
this.root.children = []
return this.fetchChildren(this.root)
}
get images() {
const getImg = (node: TreeNode): FileNodeInfo[] => {
return node.children
.map((child) => {
if (child.info.type === 'dir') {
return getImg(child)
}
if (isMediaFile(child.info.name)) {
return child.info
}
})
.filter((v) => v)
.flat(1) as FileNodeInfo[]
}
return getImg(this.root)
}
get isCompleted() {
return this.execQueue.length === 0
}
private async fetchChildren(par: TreeNode): Promise<TreeNode> {
// console.log('fetch', par.info.fullpath)
const { files } = await getTargetFolderFiles(par.info.fullpath)
par.children = sortFiles(files, this.sortMethod).map((v) => ({
info: v,
children: []
}))
this.execQueue.shift()
this.execQueue.unshift(
...par.children
.filter((v) => v.info.type === 'dir')
.map((v) => ({
fn: () => this.fetchChildren(v),
...v
}))
) // 用队列来实现dfs
return par
}
async next() {
const pkg = first(this.execQueue)
if (!pkg) {
return null
}
const res = await pkg.fn() // 这边调用时vue响应式没工作
this.execQueue = this.execQueue.slice()
this.root = { ...this.root }
return res
}
}
|