add recursive directory tree listing and start search

This commit is contained in:
joshuaboud 2022-05-13 14:49:21 -03:00
parent 2f6ae732e5
commit 8850189771
No known key found for this signature in database
GPG Key ID: 17EFB59E2A8BF50E
9 changed files with 514 additions and 395 deletions

View File

@ -1,17 +1,28 @@
<template>
<tr v-if="listView" @dblclick="doubleClickCallback" class="hover:!bg-red-600/10">
<td class="w-6 !py-0 !px-1">
<div class="relative">
<tr
v-show="!/^\./.test(entry.name) || settings?.directoryView?.showHidden"
v-if="settings.directoryView?.view === 'list'"
@dblclick="doubleClickCallback"
class="hover:!bg-red-600/10"
>
<td class="flex items-center gap-1 !pl-1">
<div :style="{ width: `${24 * level}px` }"></div>
<div class="relative w-6">
<component :is="icon" class="size-icon icon-default" />
<LinkIcon v-if="entry.type === 'link'" class="w-2 h-2 absolute right-0 bottom-0 text-default" />
</div>
</td>
<td class="!pl-1">
{{ entry.name }}
<button v-if="directoryLike" @click.stop="showEntries = !showEntries">
<ChevronDownIcon v-if="!showEntries" class="size-icon icon-default" />
<ChevronUpIcon v-else class="size-icon icon-default" />
</button>
<div>{{ entry.name }}</div>
<div v-if="entry.type === 'link'" class="inline-flex gap-1 items-center">
<div class="inline relative">
<ArrowNarrowRightIcon class="text-default size-icon-sm inline" />
<XIcon v-if="entry.target?.broken" class="icon-danger size-icon-sm absolute inset-x-0 bottom-0" />
<XIcon
v-if="entry.target?.broken"
class="icon-danger size-icon-sm absolute inset-x-0 bottom-0"
/>
</div>
<div>{{ entry.target?.rawPath ?? '' }}</div>
</div>
@ -24,36 +35,58 @@
<td v-if="settings?.directoryView?.cols?.mtime">{{ entry.mtime?.toLocaleString() ?? '-' }}</td>
<td v-if="settings?.directoryView?.cols?.atime">{{ entry.atime?.toLocaleString() ?? '-' }}</td>
</tr>
<div v-else @dblclick="doubleClickCallback" class="flex flex-col gap-content items-center">
<div class="relative">
<component
:is="icon"
:class="[settings.directoryView?.view === 'list' ? 'size-icon' : 'size-icon-xl', 'icon-default']"
/>
<LinkIcon
v-if="entry.type === 'link'"
class="size-icon-sm absolute right-0 bottom-0 text-gray-100 dark:text-gray-900"
/>
<div
v-else
v-show="!/^\./.test(entry.name) || settings?.directoryView?.showHidden"
@dblclick="doubleClickCallback"
class="flex flex-col items-center w-20 overflow-hidden"
>
<div class="relative w-20">
<component :is="icon" class="icon-default w-20 h-auto" />
<div :class="[directoryLike ? 'right-3 bottom-5' : 'right-5 bottom-3', 'inline absolute']" :title="`-> ${entry.target?.rawPath ?? '?'}`">
<LinkIcon v-if="entry.type === 'link'" :class="[entry.target?.broken ? 'text-red-300 dark:text-red-800' : 'text-gray-100 dark:text-gray-900','w-4 h-auto']" />
</div>
</div>
<div>{{ entry.name }}</div>
<div class="text-center w-full" style="overflow-wrap: break-word;">{{ entry.name }}</div>
</div>
<component
:is="DirectoryEntryList"
v-if="directoryLike && showEntries"
:path="entry.path"
:isChild="true"
:inheritedSortCallback="inheritedSortCallback"
@cd="(...args) => $emit('cd', ...args)"
@edit="(...args) => $emit('edit', ...args)"
@startProcessing="(...args) => $emit('startProcessing', ...args)"
@stopProcessing="(...args) => $emit('stopProcessing', ...args)"
ref="directoryViewRef"
:level="level + 1"
/>
</template>
<script>
import { ref, inject, watch } from 'vue';
import { DocumentIcon, FolderIcon, LinkIcon, DocumentRemoveIcon, ArrowNarrowRightIcon, XIcon } from '@heroicons/vue/solid';
import { DocumentIcon, FolderIcon, LinkIcon, DocumentRemoveIcon, ArrowNarrowRightIcon, XIcon, ChevronDownIcon, ChevronUpIcon } from '@heroicons/vue/solid';
import { settingsInjectionKey } from '../keys';
import DirectoryEntryList from './DirectoryEntryList.vue';
export default {
name: 'DirectoryEntry',
props: {
entry: Object,
listView: Boolean,
inheritedSortCallback: {
type: Function,
required: false,
default: null,
},
level: Number,
},
setup(props, { emit }) {
const settings = inject(settingsInjectionKey);
const icon = ref(FolderIcon);
const directoryLike = ref(false);
const brokenLink = ref(false);
const showEntries = ref(false);
const directoryViewRef = ref();
const doubleClickCallback = () => {
if (directoryLike.value) {
@ -63,6 +96,10 @@ export default {
}
}
const getEntries = () => {
return directoryViewRef.value?.getEntries?.();
}
watch(props.entry, () => {
if (props.entry.type === 'directory' || (props.entry.type === 'link' && props.entry.target?.type === 'directory')) {
icon.value = FolderIcon;
@ -77,8 +114,11 @@ export default {
settings,
icon,
directoryLike,
brokenLink,
showEntries,
directoryViewRef,
doubleClickCallback,
getEntries,
DirectoryEntryList,
}
},
components: {
@ -88,10 +128,15 @@ export default {
DocumentRemoveIcon,
ArrowNarrowRightIcon,
XIcon,
DirectoryEntryList,
ChevronDownIcon,
ChevronUpIcon,
},
emits: [
'cd',
'edit',
'startProcessing',
'stopProcessing',
]
}
</script>

View File

@ -0,0 +1,272 @@
<template>
<DirectoryEntry
v-for="entry, index in entries"
:key="entry.path"
:entry="entry"
:inheritedSortCallback="sortCallback"
@cd="(...args) => $emit('cd', ...args)"
@edit="(...args) => $emit('edit', ...args)"
@sortEntries="sortEntries"
@updateStats="emitStats"
@startProcessing="(...args) => $emit('startProcessing', ...args)"
@stopProcessing="(...args) => $emit('stopProcessing', ...args)"
ref="entryRefs"
:level="level"
/>
</template>
<script>
import { ref, reactive, computed, inject, watch } from 'vue';
import { useSpawn, errorString, errorStringHTML, canonicalPath } from '@45drives/cockpit-helpers';
import { notificationsInjectionKey, settingsInjectionKey } from '../keys';
import DirectoryEntry from './DirectoryEntry.vue';
export default {
name: 'DirectoryEntryList',
props: {
path: String,
sortCallback: {
type: Function,
required: false,
default: (() => 0),
},
level: Number,
},
setup(props, { emit }) {
const settings = inject(settingsInjectionKey);
const entries = ref([]);
const notifications = inject(notificationsInjectionKey);
const entryRefs = ref([]);
const sortCallbackComputed = computed(() => {
return (a, b) => {
if (settings.directoryView?.separateDirs) {
const checkA = a.type === 'link' ? (a.target?.type ?? null) : a.type;
const checkB = b.type === 'link' ? (b.target?.type ?? null) : b.type;
if (checkA === null || checkB === null)
return 0;
if (checkA === 'directory' && checkB !== 'directory')
return -1;
else if (checkA !== 'directory' && checkB === 'directory')
return 1;
}
return props.sortCallback(a, b);
}
});
const getAsyncEntryStats = (cwd, entry, modeStr, path, linkTargetRaw) => {
const procs = [];
Object.assign(entry, {
permissions: {
owner: {
read: modeStr[1] !== '-',
write: modeStr[2] !== '-',
execute: modeStr[3] !== '-',
},
group: {
read: modeStr[4] !== '-',
write: modeStr[5] !== '-',
execute: modeStr[6] !== '-',
},
other: {
read: modeStr[7] !== '-',
write: modeStr[8] !== '-',
execute: modeStr[9] !== '-',
},
acl: modeStr[10] === '+' ? {} : null,
}
});
switch (modeStr[0]) {
case 'd':
entry.type = 'directory';
break;
case '-':
entry.type = 'file';
break;
case 'p':
entry.type = 'pipe';
break;
case 'l':
entry.type = 'link';
if (linkTargetRaw) {
entry.target = {
rawPath: linkTargetRaw,
path: canonicalPath(linkTargetRaw.replace(/^(?!=\/)/, cwd + '/')),
};
emit('startProcessing');
procs.push(useSpawn(['stat', '-c', '%A', entry.target.path]).promise()
.then(state => {
getAsyncEntryStats(cwd, entry.target, state.stdout.trim());
entry.target.broken = false;
})
.catch(() => {
entry.target.broken = true;
})
.finally(() => emit('stopProcessing'))
);
}
break;
case 's':
entry.type = 'socket';
break;
case 'c':
entry.type = 'character';
break;
case 'b':
entry.type = 'block';
break;
default:
entry.type = 'unk';
break;
}
if (entry.permissions.acl && path) {
emit('startProcessing');
procs.push(useSpawn(['getfacl', '--omit-header', '--no-effective', path], { superuser: 'try' }).promise()
.then(state => {
entry.permissions.acl = state.stdout
.split('\n')
.filter(line => line && !/^\s*(?:#|$)/.test(line))
.reduce((acl, line) => {
const match = line.match(/^([^:]*):([^:]+)?:(.*)$/).slice(1);
acl[match[0]] = acl[match[0]] ?? {};
acl[match[0]][match[1] ?? '*'] = {
r: match[2][0] !== '-',
w: match[2][1] !== '-',
x: match[2][2] !== '-',
}
return acl;
}, {});
})
.catch(state => {
console.error(`failed to get ACL for ${path}:`, errorString(state));
})
.finally(() => emit('stopProcessing'))
);
}
if (path) {
emit('startProcessing');
procs.push(useSpawn(['stat', '-c', '%W:%Y:%X', path], { superuser: 'try' }).promise() // birth:modification:access
.then(state => {
const [ctimeStr, mtimeStr, atimeStr] = state.stdout.trim().split(':');
Object.assign(entry, {
ctime: new Date(parseInt(ctimeStr) * 1000),
mtime: new Date(parseInt(mtimeStr) * 1000),
atime: new Date(parseInt(atimeStr) * 1000),
});
})
.catch(state =>
notifications.value.constructNotification(`Failed to get stats for ${path}`, errorStringHTML(state), 'error')
)
.finally(() => emit('stopProcessing'))
);
}
return Promise.all(procs);
}
const getEntries = async () => {
emit('startProcessing');
try {
const cwd = props.path;
const procs = [];
procs.push(entryRefs.value.map(entryRef => entryRef.getEntries()));
let lsOutput;
try {
lsOutput = (await useSpawn(['ls', '-al', '--color=never', '--time-style=full-iso', '--quote-name', '--dereference-command-line-symlink-to-dir', cwd], { superuser: 'try' }).promise()).stdout
} catch (state) {
if (state.exit_code === 1)
lsOutput = state.stdout; // non-fatal ls error
else
throw new Error(state.stderr);
}
entries.value = lsOutput
.split('\n')
.filter(line => !/^(?:\s*$|total)/.test(line)) // remove empty lines
.map(record => {
try {
if (cwd !== props.path)
return null;
const entry = reactive({});
const fields = record.match(/^([a-z-]+\+?)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\d+(?:,\s+\d+)?)\s+([^"]+)"([^"]+)"(?:\s+->\s+"([^"]+)")?/)?.slice(1);
if (!fields) {
console.error('regex failed to match on', record);
return null;
}
entry.name = fields[6];
if (entry.name === '.' || entry.name === '..')
return null;
entry.path = canonicalPath(cwd + `/${entry.name}`);
entry.modeStr = fields[0];
entry.hardlinkCount = parseInt(fields[1]);
entry.owner = fields[2];
entry.group = fields[3];
if (/,/.test(fields[4])) {
[entry.major, entry.minor] = fields[4].split(/,\s+/);
entry.size = null;
} else {
entry.size = parseInt(fields[4]);
entry.sizeHuman = cockpit.format_bytes(entry.size, 1000).replace(/(?<!B)$/, ' B');
entry.major = entry.minor = null;
}
procs.push(getAsyncEntryStats(cwd, entry, entry.modeStr, entry.path, fields[7]));
return entry;
} catch (error) {
notifications.value.constructNotification(`Error while gathering info for ${entry.path ?? record}`, errorStringHTML(error), 'error');
return null;
}
})
.filter(entry => entry !== null)
?? [];
return Promise.all(procs).then(() => {
emitStats();
sortEntries();
})
} catch (error) {
entries.value = [];
notifications.value.constructNotification("Error getting directory entries", errorStringHTML(error), 'error');
} finally {
emit('stopProcessing');
}
}
const emitStats = () => {
emit('updateStats', entries.value.reduce((stats, entry) => {
if (entry.type === 'directory' || (entry.type === 'link' && entry.target?.type === 'directory'))
stats.dirs++;
else
stats.files++;
return stats;
}, { files: 0, dirs: 0 }));
}
const sortEntries = () => {
emit('startProcessing');
entries.value.sort(sortCallbackComputed.value);
emit('stopProcessing');
}
watch(() => props.sortCallback, sortEntries);
watch(entries, sortEntries);
watch(() => settings.directoryView?.separateDirs, sortEntries);
watch(() => props.path, getEntries, { immediate: true });
return {
settings,
entries,
entryRefs,
getEntries,
emitStats,
sortEntries,
}
},
components: {
DirectoryEntry,
},
emits: [
'cd',
'edit',
'updateStats',
'startProcessing',
'stopProcessing',
]
}
</script>

View File

@ -1,115 +1,111 @@
<template>
<Table
v-if="settings.directoryView?.view === 'list'"
emptyText="No entries."
noHeader
stickyHeaders
noShrink
noShrinkHeight="h-full"
class="rounded-lg"
>
<template #thead>
<tr>
<th class="w-6 !p-0">
<div class="flex items-center justify-center">
<LoadingSpinner v-if="processing" class="size-icon" />
</div>
</th>
<th class="!pl-1">
<div class="flex flex-row flex-nowrap gap-2">
<div class="grow">Name</div>
<SortCallbackButton
initialFuncIsMine
v-model="sortCallback"
:compareFunc="sortCallbacks.name"
/>
</div>
</th>
<th v-if="settings?.directoryView?.cols?.mode">Mode</th>
<th v-if="settings?.directoryView?.cols?.owner">
<div class="flex flex-row flex-nowrap gap-2">
<div class="grow">Owner</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.owner" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.group">
<div class="flex flex-row flex-nowrap gap-2">
<div class="grow">Group</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.group" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.size">
<div class="flex flex-row flex-nowrap gap-2">
<div class="grow">Size</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.size" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.ctime">
<div class="flex flex-row flex-nowrap gap-2">
<div class="grow">Created</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.ctime" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.mtime">
<div class="flex flex-row flex-nowrap gap-2">
<div class="grow">Modified</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.mtime" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.atime">
<div class="flex flex-row flex-nowrap gap-2">
<div class="grow">Accessed</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.atime" />
</div>
</th>
</tr>
</template>
<template #tbody>
<DirectoryEntry
v-for="entry, index in entries"
:hidden="!settings.directoryView.showHidden && /^\./.test(entry.name)"
:key="entry.path"
:entry="entry"
listView
<div class="h-full">
<Table
v-if="settings.directoryView?.view === 'list'"
emptyText="No entries."
noHeader
stickyHeaders
noShrink
noShrinkHeight="h-full"
>
<template #thead>
<tr v-if="!isChild">
<th class="!pl-1">
<div class="flex flex-row flex-nowrap gap-1 items-center">
<div class="flex items-center justify-center w-6">
<LoadingSpinner v-if="processing" class="size-icon" />
</div>
<div class="grow">Name</div>
<SortCallbackButton
initialFuncIsMine
v-model="sortCallback"
:compareFunc="sortCallbacks.name"
/>
</div>
</th>
<th v-if="settings?.directoryView?.cols?.mode">Mode</th>
<th v-if="settings?.directoryView?.cols?.owner">
<div class="flex flex-row flex-nowrap gap-2 items-center">
<div class="grow">Owner</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.owner" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.group">
<div class="flex flex-row flex-nowrap gap-2 items-center">
<div class="grow">Group</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.group" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.size">
<div class="flex flex-row flex-nowrap gap-2 items-center">
<div class="grow">Size</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.size" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.ctime">
<div class="flex flex-row flex-nowrap gap-2 items-center">
<div class="grow">Created</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.ctime" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.mtime">
<div class="flex flex-row flex-nowrap gap-2 items-center">
<div class="grow">Modified</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.mtime" />
</div>
</th>
<th v-if="settings?.directoryView?.cols?.atime">
<div class="flex flex-row flex-nowrap gap-2 items-center">
<div class="grow">Accessed</div>
<SortCallbackButton v-model="sortCallback" :compareFunc="sortCallbacks.atime" />
</div>
</th>
</tr>
</template>
<template #tbody>
<DirectoryEntryList
:path="path"
:sortCallback="sortCallback"
@cd="(...args) => $emit('cd', ...args)"
@edit="(...args) => $emit('edit', ...args)"
@updateStats="(...args) => $emit('updateStats', ...args)"
@startProcessing="processing++"
@stopProcessing="processing--"
ref="directoryEntryListRef"
:level="0"
/>
</template>
</Table>
<div v-else class="flex flex-wrap p-2 gap-2 bg-well h-full overflow-y-auto content-start">
<DirectoryEntryList
:path="path"
:sortCallback="sortCallback"
@cd="(...args) => $emit('cd', ...args)"
@edit="(...args) => $emit('edit', ...args)"
@sortEntries="sortEntries"
@updateStats="emitStats"
@updateStats="(...args) => $emit('updateStats', ...args)"
@startProcessing="processing++"
@stopProcessing="processing--"
/>
</template>
</Table>
<div v-else class="flex flex-wrap gap-well p-well bg-well h-full overflow-y-auto">
<DirectoryEntry
v-for="entry, index in entries"
:hidden="!settings.directoryView.showHidden && /^\./.test(entry.name)"
:key="entry.path"
:entry="entry"
@cd="(...args) => $emit('cd', ...args)"
@edit="(...args) => $emit('edit', ...args)"
@sortEntries="sortEntries"
@updateStats="emitStats"
/>
</div>
</div>
</template>
<script>
import { ref, reactive, computed, inject, watch } from 'vue';
import DirectoryEntry from './DirectoryEntry.vue';
import { useSpawn, errorStringHTML, canonicalPath } from '@45drives/cockpit-helpers';
import { ref, inject } from 'vue';
import Table from './Table.vue';
import { notificationsInjectionKey, settingsInjectionKey } from '../keys';
import LoadingSpinner from './LoadingSpinner.vue';
import SortCallbackButton from './SortCallbackButton.vue';
import DirectoryEntryList from './DirectoryEntryList.vue';
export default {
props: {
path: String,
},
setup(props, { emit }) {
setup() {
const settings = inject(settingsInjectionKey);
const entries = ref([]);
const processing = ref(0);
const notifications = inject(notificationsInjectionKey);
const directoryEntryListRef = ref();
const sortCallbacks = {
name: (a, b) => a.name.localeCompare(b.name),
@ -121,235 +117,22 @@ export default {
atime: (a, b) => a.atime.getTime() - b.atime.getTime(),
}
const sortCallback = ref(() => 0);
const sortCallbackComputed = computed({
get() {
return (a, b) => {
if (settings.directoryView?.separateDirs) {
const checkA = a.type === 'link' ? (a.target?.type ?? null) : a.type;
const checkB = b.type === 'link' ? (b.target?.type ?? null) : b.type;
if (checkA === null || checkB === null)
return 0;
if (checkA === 'directory' && checkB !== 'directory')
return -1;
else if (checkA !== 'directory' && checkB === 'directory')
return 1;
}
return sortCallback.value(a, b);
}
},
set(value) {
sortCallback.value = value;
}
})
const getAsyncEntryStats = (cwd, entry, modeStr, path, linkTargetRaw) => {
const procs = [];
Object.assign(entry, {
permissions: {
owner: {
read: modeStr[1] !== '-',
write: modeStr[2] !== '-',
execute: modeStr[3] !== '-',
},
group: {
read: modeStr[4] !== '-',
write: modeStr[5] !== '-',
execute: modeStr[6] !== '-',
},
other: {
read: modeStr[7] !== '-',
write: modeStr[8] !== '-',
execute: modeStr[9] !== '-',
},
acl: modeStr[10] === '+' ? {} : null,
}
});
switch (modeStr[0]) {
case 'd':
entry.type = 'directory';
break;
case '-':
entry.type = 'file';
break;
case 'p':
entry.type = 'pipe';
break;
case 'l':
entry.type = 'link';
if (linkTargetRaw) {
entry.target = {
rawPath: linkTargetRaw,
path: canonicalPath(linkTargetRaw.replace(/^(?!=\/)/, cwd + '/')),
};
processing.value++;
procs.push(useSpawn(['stat', '-c', '%A', entry.target.path]).promise()
.then(state => {
getAsyncEntryStats(cwd, entry.target, state.stdout.trim());
entry.target.broken = false;
})
.catch(() => {
entry.target.broken = true;
})
.finally(() => processing.value--)
);
}
break;
case 's':
entry.type = 'socket';
break;
case 'c':
entry.type = 'character';
break;
case 'b':
entry.type = 'block';
break;
default:
entry.type = 'unk';
break;
}
if (entry.permissions.acl && path) {
processing.value++;
procs.push(useSpawn(['getfacl', '--omit-header', '--no-effective', path], { superuser: 'try' }).promise()
.then(state => {
entry.permissions.acl = state.stdout
.split('\n')
.filter(line => line && !/^\s*(?:#|$)/.test(line))
.reduce((acl, line) => {
const match = line.match(/^([^:]*):([^:]+)?:(.*)$/).slice(1);
acl[match[0]] = acl[match[0]] ?? {};
acl[match[0]][match[1] ?? '*'] = {
r: match[2][0] !== '-',
w: match[2][1] !== '-',
x: match[2][2] !== '-',
}
return acl;
}, {});
})
.catch(state => {
console.error(`failed to get ACL for ${path}:`, errorString(state));
})
.finally(() => processing.value--)
);
}
if (path) {
processing.value++;
procs.push(useSpawn(['stat', '-c', '%W:%Y:%X', path], { superuser: 'try' }).promise() // birth:modification:access
.then(state => {
const [ctimeStr, mtimeStr, atimeStr] = state.stdout.trim().split(':');
Object.assign(entry, {
ctime: new Date(parseInt(ctimeStr) * 1000),
mtime: new Date(parseInt(mtimeStr) * 1000),
atime: new Date(parseInt(atimeStr) * 1000),
});
})
.catch(state =>
notifications.value.constructNotification(`Failed to get stats for ${path}`, errorStringHTML(state), 'error')
)
.finally(() => processing.value--)
);
}
return Promise.all(procs);
const getEntries = () => {
return directoryEntryListRef.value?.getEntries?.();
}
const getEntries = async () => {
processing.value++;
try {
const cwd = props.path;
let lsOutput;
try {
lsOutput = (await useSpawn(['ls', '-al', '--color=never', '--time-style=full-iso', '--quote-name', '--dereference-command-line-symlink-to-dir', cwd], { superuser: 'try' }).promise()).stdout
} catch (state) {
if (state.exit_code === 1)
lsOutput = state.stdout; // non-fatal ls error
else
throw new Error(state.stderr);
}
const procs = [];
entries.value = lsOutput
.split('\n')
.filter(line => !/^(?:\s*$|total)/.test(line)) // remove empty lines
.map(record => {
try {
if (cwd !== props.path)
return null;
const entry = reactive({});
const fields = record.match(/^([a-z-]+\+?)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\d+(?:,\s+\d+)?)\s+([^"]+)"([^"]+)"(?:\s+->\s+"([^"]+)")?/)?.slice(1);
if (!fields) {
console.error('regex failed to match on', record);
return null;
}
entry.name = fields[6];
if (entry.name === '.' || entry.name === '..')
return null;
entry.path = canonicalPath(cwd + `/${entry.name}`);
entry.modeStr = fields[0];
entry.hardlinkCount = parseInt(fields[1]);
entry.owner = fields[2];
entry.group = fields[3];
if (/,/.test(fields[4])) {
[entry.major, entry.minor] = fields[4].split(/,\s+/);
entry.size = null;
} else {
entry.size = parseInt(fields[4]);
entry.sizeHuman = cockpit.format_bytes(entry.size, 1000).replace(/(?<!B)$/, ' B');
entry.major = entry.minor = null;
}
procs.push(getAsyncEntryStats(cwd, entry, entry.modeStr, entry.path, fields[7]));
return entry;
} catch (error) {
notifications.value.constructNotification(`Error while gathering info for ${entry.path ?? record}`, errorStringHTML(error), 'error');
return null;
}
})
.filter(entry => entry !== null)
?? [];
Promise.all(procs).then(() => {
emitStats();
sortEntries();
})
} catch (error) {
entries.value = [];
notifications.value.constructNotification("Error getting directory entries", errorStringHTML(error), 'error');
} finally {
processing.value--;
}
}
const emitStats = () => {
emit('updateStats', entries.value.reduce((stats, entry) => {
if (entry.type === 'directory' || (entry.type === 'link' && entry.target?.type === 'directory'))
stats.dirs++;
else
stats.files++;
return stats;
}, { files: 0, dirs: 0 }));
}
const sortEntries = () => {
processing.value++;
entries.value.sort(sortCallbackComputed.value);
processing.value--;
}
watch(sortCallback, sortEntries);
watch(entries, sortEntries);
watch(() => settings.directoryView?.separateDirs, sortEntries);
watch(() => props.path, getEntries, { immediate: true });
return {
settings,
entries,
processing,
directoryEntryListRef,
sortCallbacks,
sortCallback,
getEntries,
emitStats,
sortEntries,
}
},
components: {
DirectoryEntry,
DirectoryEntryList,
Table,
LoadingSpinner,
SortCallbackButton,

View File

@ -1,6 +1,6 @@
<template>
<div class="flex items-center cursor-text h-10" @click="typing = true">
<input v-if="typing" v-model="pathInput" type="text" class="w-full input-textlike" @change="$emit('cd', canonicalPath(pathInput))" ref="inputRef" @focusout="typing = false" />
<input v-if="typing" v-model="pathInput" type="text" class="block w-full input-textlike" @change="$emit('cd', canonicalPath(pathInput))" ref="inputRef" @focusout="typing = false" />
<div v-else class="inline-flex items-center gap-1">
<template v-for="segment, index in pathArr" :key="index">
<ChevronRightIcon v-if="index > 0" class="size-icon icon-default" />

View File

@ -16,7 +16,7 @@
<LabelledSwitch v-model="settings.directoryView.showHidden">Show hidden files</LabelledSwitch>
<LabelledSwitch
v-model="booleanAnalogs.directoryView.view.bool"
>{{ booleanAnalogs.directoryView.view.bool ? "List view" : "Grid view" }}</LabelledSwitch>
>List view</LabelledSwitch>
<LabelledSwitch v-model="settings.directoryView.separateDirs">Separate directories while sorting</LabelledSwitch>
</div>
<div v-if="booleanAnalogs.directoryView.view.bool" class="self-stretch">
@ -198,7 +198,6 @@ export default {
}
},
});
console.log(settings);
watch(settings, () => {
localStorage.setItem(settingsStorageKey, JSON.stringify(settings));

View File

@ -1,4 +1,4 @@
import { useSpawn } from '@45drives/cockpit-helpers';
import { useSpawn, errorString } from '@45drives/cockpit-helpers';
/** Run test with given expression and return boolean result. Throws on abnormal errors.
*

View File

@ -24,7 +24,6 @@ const router = createRouter({
});
router.beforeEach((to, from, next) => {
console.log(to);
if (to.name === 'redirectToBrowse') {
const lastLocation = localStorage.getItem(lastPathStorageKey) ?? '/';
next(`/browse${lastLocation}`);

View File

@ -1,71 +1,88 @@
<template>
<div class="grow overflow-hidden">
<div class="h-full flex flex-col items-stretch">
<div class="flex gap-buttons items-stretch divide-x divide-default">
<div class="button-group-row px-4 py-2">
<button
class="p-2 rounded-lg hover:bg-accent relative"
:disabled="!pathHistory.backAllowed()"
@click="back()"
@mouseenter="backHistoryDropdown.mouseEnter"
@mouseleave="backHistoryDropdown.mouseLeave"
>
<ArrowLeftIcon class="size-icon icon-default" />
<ChevronDownIcon
class="w-3 h-3 icon-default absolute bottom-1 right-1"
v-if="pathHistory.backAllowed()"
/>
<div
v-if="backHistoryDropdown.showDropdown"
class="absolute top-full left-0 flex flex-col items-stretch z-50 bg-default shadow-lg rounded-lg overflow-y-auto max-h-80"
<div class="flex items-stretch divide-x divide-y divide-default flex-wrap">
<div class="flex items-stretch divide-x divide-default grow-[6] basis-0">
<div class="button-group-row px-4 py-2">
<button
class="p-2 rounded-lg hover:bg-accent relative"
:disabled="!pathHistory.backAllowed()"
@click="back()"
@mouseenter="backHistoryDropdown.mouseEnter"
@mouseleave="backHistoryDropdown.mouseLeave"
>
<ArrowLeftIcon class="size-icon icon-default" />
<ChevronDownIcon
class="w-3 h-3 icon-default absolute bottom-1 right-1"
v-if="pathHistory.backAllowed()"
/>
<div
v-for="item, index in pathHistory.stack.slice(0, pathHistory.index).reverse()"
:key="index"
@click="pathHistory.index = pathHistory.index - index"
class="hover:text-white hover:bg-red-600 px-4 py-2 text-sm text-left whitespace-nowrap"
>{{ item }}</div>
</div>
</button>
<button
class="p-2 rounded-lg hover:bg-accent relative"
:disabled="!pathHistory.forwardAllowed()"
@click="forward()"
@mouseenter="forwardHistoryDropdown.mouseEnter"
@mouseleave="forwardHistoryDropdown.mouseLeave"
>
<ArrowRightIcon class="size-icon icon-default" />
<ChevronDownIcon
class="w-3 h-3 icon-default absolute bottom-1 right-1"
v-if="pathHistory.forwardAllowed()"
/>
<div
v-if="forwardHistoryDropdown.showDropdown"
class="absolute top-full left-0 flex flex-col items-stretch z-50 bg-default shadow-lg rounded-lg overflow-y-auto max-h-80"
v-if="backHistoryDropdown.showDropdown"
class="absolute top-full left-0 flex flex-col items-stretch z-50 bg-default shadow-lg rounded-lg overflow-y-auto max-h-80"
>
<div
v-for="item, index in pathHistory.stack.slice(0, pathHistory.index).reverse()"
:key="index"
@click="pathHistory.index = pathHistory.index - index"
class="hover:text-white hover:bg-red-600 px-4 py-2 text-sm text-left whitespace-nowrap"
>{{ item }}</div>
</div>
</button>
<button
class="p-2 rounded-lg hover:bg-accent relative"
:disabled="!pathHistory.forwardAllowed()"
@click="forward()"
@mouseenter="forwardHistoryDropdown.mouseEnter"
@mouseleave="forwardHistoryDropdown.mouseLeave"
>
<ArrowRightIcon class="size-icon icon-default" />
<ChevronDownIcon
class="w-3 h-3 icon-default absolute bottom-1 right-1"
v-if="pathHistory.forwardAllowed()"
/>
<div
v-for="item, index in pathHistory.stack.slice(pathHistory.index + 1)"
:key="index"
@click="pathHistory.index = pathHistory.index + index"
class="hover:text-white hover:bg-red-600 px-4 py-2 text-sm text-left whitespace-nowrap"
>{{ item }}</div>
</div>
</button>
<button class="p-2 rounded-lg hover:bg-accent" @click="up()">
<ArrowUpIcon class="size-icon icon-default" />
</button>
<button class="p-2 rounded-lg hover:bg-accent" @click="directoryViewRef.getEntries()">
<RefreshIcon class="size-icon icon-default" />
</button>
v-if="forwardHistoryDropdown.showDropdown"
class="absolute top-full left-0 flex flex-col items-stretch z-50 bg-default shadow-lg rounded-lg overflow-y-auto max-h-80"
>
<div
v-for="item, index in pathHistory.stack.slice(pathHistory.index + 1)"
:key="index"
@click="pathHistory.index = pathHistory.index + index"
class="hover:text-white hover:bg-red-600 px-4 py-2 text-sm text-left whitespace-nowrap"
>{{ item }}</div>
</div>
</button>
<button class="p-2 rounded-lg hover:bg-accent" @click="up()">
<ArrowUpIcon class="size-icon icon-default" />
</button>
<button class="p-2 rounded-lg hover:bg-accent" @click="directoryViewRef.getEntries()">
<RefreshIcon class="size-icon icon-default" />
</button>
</div>
<div class="grow px-4 py-2">
<PathBreadCrumbs :path="pathHistory.current() ?? '/'" @cd="newPath => cd(newPath)" />
</div>
</div>
<div class="grow card-header px-4 py-2">
<PathBreadCrumbs :path="pathHistory.current() ?? '/'" @cd="newPath => cd(newPath)" />
<div class="grow shrink-0 px-4 py-2">
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<SearchIcon class="size-icon icon-default" aria-hidden="true" />
</div>
<input
type="text"
class="block input-textlike w-full pl-10"
v-model="searchFilter"
placeholder="Search in directory"
/>
</div>
</div>
</div>
<div class="grow overflow-hidden">
<DirectoryView
:path="pathHistory.current() ?? '/'"
@cd="newPath => cd(newPath)"
@edit="(...args) => console.log('edit', ...args)"
@updateStats="stats => $emit('updateFooterText', `${stats.files} file${stats.files === 1 ? '' : 's'}, ${stats.dirs} director${stats.dirs === 1 ? 'y' : 'ies'}`)"
ref="directoryViewRef"
/>
@ -82,7 +99,7 @@ import { errorStringHTML, canonicalPath } from '@45drives/cockpit-helpers';
import PathBreadCrumbs from '../components/PathBreadCrumbs.vue';
import { checkIfExists, checkIfAllowed } from '../mode';
import { notificationsInjectionKey, pathHistoryInjectionKey, lastPathStorageKey } from '../keys';
import { ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon, RefreshIcon, ChevronDownIcon } from '@heroicons/vue/solid';
import { ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon, RefreshIcon, ChevronDownIcon, SearchIcon } from '@heroicons/vue/solid';
export default {
setup() {
@ -90,6 +107,7 @@ export default {
const route = useRoute();
const pathHistory = inject(pathHistoryInjectionKey);
const directoryViewRef = ref();
const searchFilter = ref("");
const backHistoryDropdown = reactive({
showDropdown: false,
timeoutHandle: null,
@ -173,8 +191,10 @@ export default {
return {
cockpit,
console,
pathHistory,
directoryViewRef,
searchFilter,
backHistoryDropdown,
forwardHistoryDropdown,
cd,
@ -191,6 +211,7 @@ export default {
ArrowUpIcon,
RefreshIcon,
ChevronDownIcon,
SearchIcon,
},
emits: [
'updateFooterText'

View File

@ -687,9 +687,9 @@ reusify@^1.0.4:
integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==
rollup@^2.59.0:
version "2.72.1"
resolved "https://registry.yarnpkg.com/rollup/-/rollup-2.72.1.tgz#861c94790537b10008f0ca0fbc60e631aabdd045"
integrity sha512-NTc5UGy/NWFGpSqF1lFY8z9Adri6uhyMLI6LvPAXdBKoPRFhIIiBUpt+Qg2awixqO3xvzSijjhnb4+QEZwJmxA==
version "2.73.0"
resolved "https://registry.yarnpkg.com/rollup/-/rollup-2.73.0.tgz#128fef4b333fd92d02d6929afbb6ee38d7feb32d"
integrity sha512-h/UngC3S4Zt28mB3g0+2YCMegT5yoftnQplwzPqGZcKvlld5e+kT/QRmJiL+qxGyZKOYpgirWGdLyEO1b0dpLQ==
optionalDependencies:
fsevents "~2.3.2"