Refactoring Document storage #5

Merged
leo merged 7 commits from doc-class into main 2023-11-13 17:52:58 +00:00
9 changed files with 65 additions and 184 deletions
Showing only changes of commit f0fc4a7d30 - Show all commits

View File

@ -17,7 +17,7 @@ import type { ComputedRef } from 'vue'
import type HeaderMain from '@/components/HeaderMain.vue'
import { onMounted, onUnmounted, ref, watchEffect } from 'vue'
import { loadSession, watchConnect, watchDisconnect } from '@/repositories/WS'
import { useDocumentStore } from '@/stores/documents'
import { useMainStore } from '@/stores/main'
import { computed } from 'vue'
import Router from '@/router/index'
@ -27,7 +27,7 @@ interface Path {
pathList: string[]
query: string
}
const documentStore = useDocumentStore()
const store = useMainStore()
const path: ComputedRef<Path> = computed(() => {
const p = decodeURIComponent(Router.currentRoute.value.path).split('//')
const pathList = p[0].split('/').filter(value => value !== '')
@ -39,7 +39,7 @@ const path: ComputedRef<Path> = computed(() => {
}
})
watchEffect(() => {
document.title = path.value.path.replace(/\/$/, '').split('/').pop() || documentStore.server.name || 'Cista Storage'
document.title = path.value.path.replace(/\/$/, '').split('/').pop() || store.server.name || 'Cista Storage'
})
onMounted(loadSession)
onMounted(watchConnect)
@ -48,7 +48,7 @@ const headerMain = ref<typeof HeaderMain | null>(null)
let vert = 0
let timer: any = null
const globalShortcutHandler = (event: KeyboardEvent) => {
const fileExplorer = documentStore.fileExplorer as any
const fileExplorer = store.fileExplorer as any
if (!fileExplorer) return
const c = fileExplorer.isCursor()
const keyup = event.type === 'keyup'
@ -124,3 +124,4 @@ onUnmounted(() => {
})
export type { Path }
</script>
@/stores/main

View File

@ -36,11 +36,11 @@
<input
type="checkbox"
tabindex="-1"
:checked="documentStore.selected.has(doc.key)"
:checked="store.selected.has(doc.key)"
@change="
($event.target as HTMLInputElement).checked
? documentStore.selected.add(doc.key)
: documentStore.selected.delete(doc.key)
? store.selected.add(doc.key)
: store.selected.delete(doc.key)
"
/>
</td>
@ -80,7 +80,7 @@
<script setup lang="ts">
import { ref, computed, watchEffect, shallowRef, onMounted, onUnmounted } from 'vue'
import { useDocumentStore } from '@/stores/documents'
import { useMainStore } from '@/stores/main'
import { Doc } from '@/repositories/Document'
import FileRenameInput from './FileRenameInput.vue'
import { connect, controlUrl } from '@/repositories/WS'
@ -91,7 +91,7 @@ const props = defineProps<{
path: Array<string>
documents: Doc[]
}>()
const documentStore = useDocumentStore()
const store = useMainStore()
const router = useRouter()
const url_for = (doc: Doc) => {
const p = doc.loc ? `${doc.loc}/${doc.name}` : doc.name
@ -159,10 +159,10 @@ defineExpose({
cursorSelect() {
const doc = cursor.value
if (!doc) return
if (documentStore.selected.has(doc.key)) {
documentStore.selected.delete(doc.key)
if (store.selected.has(doc.key)) {
store.selected.delete(doc.key)
} else {
documentStore.selected.add(doc.key)
store.selected.add(doc.key)
}
this.cursorMove(1)
},
@ -187,8 +187,8 @@ defineExpose({
for (let p = begin; p !== end; p = increment(p, 1)) {
if (p === N) continue
const key = documents[p].key
if (documentStore.selected.has(key)) documentStore.selected.delete(key)
else documentStore.selected.add(key)
if (store.selected.has(key)) store.selected.delete(key)
else store.selected.add(key)
}
}
// @ts-ignore
@ -278,7 +278,7 @@ const selectionIndeterminate = computed({
get: () => {
return (
props.documents.length > 0 &&
props.documents.some((doc: Doc) => documentStore.selected.has(doc.key)) &&
props.documents.some((doc: Doc) => store.selected.has(doc.key)) &&
!allSelected.value
)
},
@ -289,16 +289,16 @@ const allSelected = computed({
get: () => {
return (
props.documents.length > 0 &&
props.documents.every((doc: Doc) => documentStore.selected.has(doc.key))
props.documents.every((doc: Doc) => store.selected.has(doc.key))
)
},
set: (value: boolean) => {
console.log('Setting allSelected', value)
for (const doc of props.documents) {
if (value) {
documentStore.selected.add(doc.key)
store.selected.add(doc.key)
} else {
documentStore.selected.delete(doc.key)
store.selected.delete(doc.key)
}
}
}
@ -456,3 +456,4 @@ tbody .selection input {
color: #888;
}
</style>
@/stores/main

View File

@ -1,15 +1,15 @@
<template>
<nav class="headermain">
<div class="buttons">
<template v-if="documentStore.error">
<div class="error-message" @click="documentStore.error = ''">{{ documentStore.error }}</div>
<template v-if="store.error">
<div class="error-message" @click="store.error = ''">{{ store.error }}</div>
<div class="smallgap"></div>
</template>
<UploadButton :path="props.path" />
<SvgButton
name="create-folder"
data-tooltip="New folder"
@click="() => documentStore.fileExplorer!.newFolder()"
@click="() => store.fileExplorer!.newFolder()"
/>
<slot></slot>
<div class="spacer smallgap"></div>
@ -32,12 +32,12 @@
</template>
<script setup lang="ts">
import { useDocumentStore } from '@/stores/documents'
import { useMainStore } from '@/stores/main'
import { ref, nextTick, watchEffect } from 'vue'
import ContextMenu from '@imengyu/vue3-context-menu'
import router from '@/router';
const documentStore = useDocumentStore()
const store = useMainStore()
const showSearchInput = ref<boolean>(false)
const search = ref<HTMLInputElement | null>()
const searchButton = ref<HTMLButtonElement | null>()
@ -76,10 +76,10 @@ watchEffect(() => {
const settingsMenu = (e: Event) => {
// show the context menu
const items = []
if (documentStore.user.isLoggedIn) {
items.push({ label: `Logout ${documentStore.user.username ?? ''}`, onClick: () => documentStore.logout() })
if (store.user.isLoggedIn) {
items.push({ label: `Logout ${store.user.username ?? ''}`, onClick: () => store.logout() })
} else {
items.push({ label: 'Login', onClick: () => documentStore.loginDialog() })
items.push({ label: 'Login', onClick: () => store.loginDialog() })
}
ContextMenu.showContextMenu({
// @ts-ignore
@ -115,3 +115,4 @@ input[type='search'] {
max-width: 30vw;
}
</style>
@/stores/main

View File

@ -1,29 +1,29 @@
<template>
<template v-if="documentStore.selected.size">
<template v-if="store.selected.size">
<div class="smallgap"></div>
<p class="select-text">{{ documentStore.selected.size }} selected </p>
<p class="select-text">{{ store.selected.size }} selected </p>
<SvgButton name="download" data-tooltip="Download" @click="download" />
<SvgButton name="copy" data-tooltip="Copy here" @click="op('cp', dst)" />
<SvgButton name="paste" data-tooltip="Move here" @click="op('mv', dst)" />
<SvgButton name="trash" data-tooltip="Delete " @click="op('rm')" />
<button class="action-button unselect" data-tooltip="Unselect all" @click="documentStore.selected.clear()"></button>
<button class="action-button unselect" data-tooltip="Unselect all" @click="store.selected.clear()"></button>
</template>
</template>
<script setup lang="ts">
import {connect, controlUrl} from '@/repositories/WS'
import { useDocumentStore } from '@/stores/documents'
import { useMainStore } from '@/stores/main'
import { computed } from 'vue'
import type { SelectedItems } from '@/repositories/Document'
const documentStore = useDocumentStore()
const store = useMainStore()
const props = defineProps({
path: Array<string>
})
const dst = computed(() => props.path!.join('/'))
const op = (op: string, dst?: string) => {
const sel = documentStore.selectedFiles
const sel = store.selectedFiles
const msg = {
op,
sel: sel.keys.map(key => {
@ -38,12 +38,12 @@ const op = (op: string, dst?: string) => {
const res = JSON.parse(ev.data)
if ('error' in res) {
console.error('Control socket error', msg, res.error)
documentStore.error = res.error.message
store.error = res.error.message
return
} else if (res.status === 'ack') {
console.log('Control ack OK', res)
control.close()
documentStore.selected.clear()
store.selected.clear()
return
} else console.log('Unknown control response', msg, res)
}
@ -108,17 +108,17 @@ const filesystemdl = async (sel: SelectedItems, handle: FileSystemDirectoryHandl
}
const download = async () => {
const sel = documentStore.selectedFiles
const sel = store.selectedFiles
console.log('Download', sel)
if (sel.keys.length === 0) {
console.warn('Attempted download but no files found. Missing selected keys:', sel.missing)
documentStore.selected.clear()
store.selected.clear()
return
}
// Plain old a href download if only one file (ignoring any folders)
const files = sel.recursive.filter(([rel, full, doc]) => !doc.dir)
if (files.length === 1) {
documentStore.selected.clear()
store.selected.clear()
return linkdl(`/files/${files[0][1]}`)
}
// Use FileSystem API if multiple files and the browser supports it
@ -130,7 +130,7 @@ const download = async () => {
mode: 'readwrite'
})
filesystemdl(sel, handle).then(() => {
documentStore.selected.clear()
store.selected.clear()
})
return
} catch (e) {
@ -140,7 +140,7 @@ const download = async () => {
// Otherwise, zip and download
const name = sel.keys.length === 1 ? sel.docs[sel.keys[0]].name : 'download'
linkdl(`/zip/${Array.from(sel.keys).join('+')}/${name}.zip`)
documentStore.selected.clear()
store.selected.clear()
}
</script>
@ -152,3 +152,4 @@ const download = async () => {
text-overflow: ellipsis;
}
</style>
@/stores/main

View File

@ -39,10 +39,10 @@
import { reactive, ref } from 'vue'
import { loginUser } from '@/repositories/User'
import type { ISimpleError } from '@/repositories/Client'
import { useDocumentStore } from '@/stores/documents'
import { useMainStore } from '@/stores/main'
const confirmLoading = ref<boolean>(false)
const store = useDocumentStore()
const store = useMainStore()
const loginForm = reactive({
username: '',
@ -99,3 +99,4 @@ const login = async () => {
height: 1em;
}
</style>
@/stores/main

View File

@ -1,12 +1,12 @@
<script setup lang="ts">
import { connect, uploadUrl } from '@/repositories/WS';
import { useDocumentStore } from '@/stores/documents'
import { useMainStore } from '@/stores/main'
import { collator } from '@/utils';
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
const fileInput = ref()
const folderInput = ref()
const documentStore = useDocumentStore()
const store = useMainStore()
const props = defineProps({
path: Array<string>
})
@ -75,7 +75,7 @@ const uploadFiles = (infiles: File[]) => {
const uploadCloudFiles = (files: CloudFile[]) => {
const dotfiles = files.filter(f => f.cloudName.includes('/.'))
if (dotfiles.length) {
documentStore.error = "Won't upload dotfiles"
store.error = "Won't upload dotfiles"
console.log("Dotfiles omitted", dotfiles)
files = files.filter(f => !f.cloudName.includes('/.'))
}
@ -171,13 +171,13 @@ const WSCreate = async () => await new Promise<WebSocket>(resolve => {
open(ev: Event) { resolve(ws) },
error(ev: Event) {
console.error('Upload socket error', ev)
documentStore.error = 'Upload socket error'
store.error = 'Upload socket error'
},
message(ev: MessageEvent) {
const res = JSON.parse(ev!.data)
if ('error' in res) {
console.error('Upload socket error', res.error)
documentStore.error = res.error.message
store.error = res.error.message
return
}
if (res.status === 'ack') {
@ -302,3 +302,4 @@ span {
.position { min-width: 4em }
.speed { min-width: 4em }
</style>
@/stores/main

View File

@ -1,4 +1,4 @@
import { useDocumentStore } from "@/stores/documents"
import { useMainStore } from "@/stores/main"
import type { FileEntry, UpdateEntry, errorEvent } from "./Document"
export const controlUrl = '/api/control'
@ -12,7 +12,7 @@ let wsWatch = null as WebSocket | null
export const loadSession = () => {
const s = localStorage['cista-files']
if (!s) return false
const store = useDocumentStore()
const store = useMainStore()
try {
tree = JSON.parse(s)
store.updateRoot(tree)
@ -39,7 +39,7 @@ export const watchConnect = () => {
clearTimeout(watchTimeout)
watchTimeout = null
}
const store = useDocumentStore()
const store = useMainStore()
if (store.error !== 'Reconnecting...') store.error = 'Connecting...'
console.log(store.error)
@ -81,7 +81,7 @@ export const watchDisconnect = () => {
let watchTimeout: any = null
const watchReconnect = (event: MessageEvent) => {
const store = useDocumentStore()
const store = useMainStore()
if (store.connected) {
console.warn("Disconnected from server", event)
store.connected = false
@ -114,7 +114,7 @@ const handleWatchMessage = (event: MessageEvent) => {
}
function handleRootMessage({ root }: { root: FileEntry[] }) {
const store = useDocumentStore()
const store = useMainStore()
console.log('Watch root', root)
store.updateRoot(root)
tree = root
@ -122,7 +122,7 @@ function handleRootMessage({ root }: { root: FileEntry[] }) {
}
function handleUpdateMessage(updateData: { update: UpdateEntry[] }) {
const store = useDocumentStore()
const store = useMainStore()
const update = updateData.update
console.log('Watch update', update)
if (!tree) return console.error('Watch update before root')
@ -146,7 +146,7 @@ function handleUpdateMessage(updateData: { update: UpdateEntry[] }) {
}
function handleError(msg: errorEvent) {
const store = useDocumentStore()
const store = useMainStore()
if (msg.error.code === 401) {
store.user.isOpenLoginModal = true
store.user.isLoggedIn = false

View File

@ -1,126 +0,0 @@
import type { FileEntry, FUID, SelectedItems } from '@/repositories/Document'
import { Doc } from '@/repositories/Document'
import { defineStore } from 'pinia'
import { collator } from '@/utils'
import { logoutUser } from '@/repositories/User'
import { watchConnect } from '@/repositories/WS'
import { shallowRef } from 'vue'
type User = {
username: string
privileged: boolean
isOpenLoginModal: boolean
isLoggedIn: boolean
}
export const useDocumentStore = defineStore({
id: 'documents',
state: () => ({
document: shallowRef<Doc[]>([]),
selected: new Set<FUID>(),
fileExplorer: null as any,
error: '' as string,
connected: false,
server: {} as Record<string, any>,
user: {
username: '',
privileged: false,
isLoggedIn: false,
isOpenLoginModal: false
} as User
}),
actions: {
updateRoot(root: FileEntry[]) {
const docs = []
let loc = [] as string[]
for (const [level, name, key, mtime, size, isfile] of root) {
loc = loc.slice(0, level - 1)
docs.push(new Doc({
name,
loc: level ? loc.join('/') : '/',
key,
size,
mtime,
dir: !isfile,
}))
loc.push(name)
}
this.document = docs
},
login(username: string, privileged: boolean) {
this.user.username = username
this.user.privileged = privileged
this.user.isLoggedIn = true
this.user.isOpenLoginModal = false
if (!this.connected) watchConnect()
},
loginDialog() {
this.user.isOpenLoginModal = true
},
async logout() {
console.log("Logout")
await logoutUser()
this.$reset()
localStorage.clear()
history.go() // Reload page
}
},
getters: {
isUserLogged(): boolean {
return this.user.isLoggedIn
},
recentDocuments(): Doc[] {
const ret = [...this.document]
ret.sort((a, b) => b.mtime - a.mtime)
return ret
},
largeDocuments(): Doc[] {
const ret = [...this.document]
ret.sort((a, b) => b.size - a.size)
return ret
},
selectedFiles(): SelectedItems {
const selected = this.selected
const found = new Set<FUID>()
const ret: SelectedItems = {
missing: new Set(),
docs: {},
keys: [],
recursive: [],
}
for (const doc of this.document) {
if (selected.has(doc.key)) {
found.add(doc.key)
ret.keys.push(doc.key)
ret.docs[doc.key] = doc
}
}
// What did we not select?
for (const key of selected) if (!found.has(key)) ret.missing.add(key)
// Build a flat list including contents recursively
const relnames = new Set<string>()
function add(rel: string, full: string, doc: Doc) {
if (!doc.dir && relnames.has(rel)) throw Error(`Multiple selections conflict for: ${rel}`)
relnames.add(rel)
ret.recursive.push([rel, full, doc])
}
for (const key of ret.keys) {
const base = ret.docs[key]
const basepath = base.loc ? `${base.loc}/${base.name}` : base.name
const nremove = base.loc.length
add(base.name, basepath, base)
for (const doc of this.document) {
if (doc.loc === basepath || doc.loc.startsWith(basepath) && doc.loc[basepath.length] === '/') {
const full = doc.loc ? `${doc.loc}/${doc.name}` : doc.name
const rel = full.slice(nremove)
add(rel, full, doc)
}
}
}
// Sort by rel (name stored as on download)
ret.recursive.sort((a, b) => collator.compare(a[0], b[0]))
return ret
}
}
})

View File

@ -10,11 +10,11 @@
<script setup lang="ts">
import { watchEffect, ref, computed } from 'vue'
import { useDocumentStore } from '@/stores/documents'
import { useMainStore } from '@/stores/main'
import Router from '@/router/index'
import { needleFormat, localeIncludes, collator } from '@/utils';
const documentStore = useDocumentStore()
const store = useMainStore()
const fileExplorer = ref()
const props = defineProps<{
path: Array<string>
@ -24,12 +24,12 @@ const documents = computed(() => {
const loc = props.path.join('/')
const query = props.query
// List the current location
if (!query) return documentStore.document.filter(doc => doc.loc === loc)
if (!query) return store.document.filter(doc => doc.loc === loc)
// Find up to 100 newest documents that match the search
const needle = needleFormat(query)
let limit = 100
let docs = []
for (const doc of documentStore.recentDocuments) {
for (const doc of store.recentDocuments) {
if (localeIncludes(doc.haystack, needle)) {
docs.push(doc)
if (--limit === 0) break
@ -53,6 +53,7 @@ const documents = computed(() => {
})
watchEffect(() => {
documentStore.fileExplorer = fileExplorer.value
store.fileExplorer = fileExplorer.value
})
</script>
@/stores/main