12 Commits

Author SHA1 Message Date
Leo Vasanko
2978e0c968 Better special handling for root Document. Restore live updates of relative modified times. 2023-11-12 20:09:29 +00:00
Leo Vasanko
540e825cc3 Watching code cleanup 2023-11-12 19:58:37 +00:00
Leo Vasanko
0be72827db Remove test.zip generation 2023-11-12 19:40:05 +00:00
Leo Vasanko
88aca511e7 Colored file size 2023-11-12 19:38:42 +00:00
Leo Vasanko
be1c4c1504 Fixes to URL path handling, search query on URL 2023-11-12 19:38:23 +00:00
Leo Vasanko
00a4297c0b New filelist format on frontend 2023-11-12 19:37:17 +00:00
Leo Vasanko
ef5e37187d Completely revamped file list format. Fixes to zip creation. 2023-11-12 19:35:20 +00:00
Leo Vasanko
a70549e6ec Formatting 2023-11-12 12:08:31 +00:00
Leo Vasanko
535905780a Refactor file modified/size fields components, style different sizes 2023-11-12 11:55:28 +00:00
Leo Vasanko
82bc449bbc Rename frontend dir, update README. 2023-11-11 14:54:30 +00:00
Leo Vasanko
5d32396127 Modified column needs more space 2023-11-11 14:49:46 +00:00
Leo Vasanko
84ce4b9220 Fix various typing errors in backend. 2023-11-11 14:49:23 +00:00
42 changed files with 763 additions and 1707 deletions

145
README.md
View File

@@ -1,118 +1,27 @@
# Cista Web Storage # Web File Storage
<img src="https://git.zi.fi/Vasanko/cista-storage/raw/branch/main/docs/cista.webp" align=left width=250> Run directly from repository with Hatch (or use pip install as usual):
Cista takes its name from the ancient *cistae*, metal containers used by Greeks and Egyptians to safeguard valuable items. This modern application provides a browser interface for secure and accessible file storage, echoing the trust and reliability of its historical namesake. ```sh
hatch run cista -l :3000 /path/to/files
This is a cutting-edge **file and document server** designed for speed, efficiency, and unparalleled ease of use. Experience **lightning-fast browsing**, thanks to the file list maintained directly in your browser and updated from server filesystem events, coupled with our highly optimized code. Fully **keyboard-navigable** and with a responsive layout, Cista flawlessly adapts to your devices, providing a seamless experience wherever you are. Our powerful **instant search** means you're always just a few keystrokes away from finding exactly what you need. Press **1/2/3** to switch ordering, navigate with all four arrow keys (+Shift to select). Or click your way around on **breadcrumbs that remember where you were**. ```
The Cista project started as an inevitable remake of [Droppy](https://github.com/droppyjs/droppy) which we used and loved despite its numerous bugs. Cista Storage stands out in handling even the most exotic filenames, ensuring a smooth experience where others falter. Settings incl. these arguments are stored to config file on the first startup and later `hatch run cista` is sufficient. If the `cista` script is missing, consider `pip install -e .` (within `hatch shell`) or some other trickery (known issue with installs made prior to adding the startup script).
All of this is wrapped in an intuitive interface with automatic light and dark themes, making Cista Storage the ideal choice for anyone seeking a reliable, versatile, and quick file storage solution. Quickly setup your own Cista where your files are just a click away, safe, and always accessible. Create your user account:
Experience Cista by visiting [Cista Demo](https://drop.zi.fi) for a test run and perhaps upload something... ```sh
hatch run cista --user admin --privileged
```
## Getting Started
### Installation ## Build frontend
To install the cista application, use: Frontend needs to be built before using and after any frontend changes:
```fish ```sh
pip install cista cd frontend
``` npm install
npm run build
Note: Some Linux distributions might need `--break-system-packages` to install Python packages, which are safely installed in the user's home folder. As an alternative to avoid installation, run it with command `pipx run cista` ```
### Running the Server This will place the front in `cista/wwwroot` from where the backend server delivers it, and that also gets included in the Python package built via `hatch build`.
Create an account: (or run a public server without authentication)
```fish
cista --user yourname --privileged
```
Serve your files at http://localhost:8000:
```fish
cista -l :8000 /path/to/files
```
The server remembers its settings in the config folder (default `~/.local/share/cista/`), including the listen port and directory, for future runs without arguments.
### Internet Access
To use your own TLS certificates, place them in the config folder and run:
```fish
cista -l cista.example.com
```
Most admins instead find the [Caddy](https://caddyserver.com/) web server convenient for its auto TLS certificates and all. A proxy also allows running multiple web services or Cista instances on the same IP address but different (sub)domains.
`/etc/caddy/Caddyfile`:
```Caddyfile
cista.example.com {
reverse_proxy :8000
}
```
## Development setup
For rapid development, we use the Vite development server for the Vue frontend, while running the backend on port 8000 that Vite proxies backend requests to. Each server live reloads whenever its code or configuration are modified.
```fish
cd frontend
npm install
npm run dev
```
Concurrently, start the backend on another terminal:
```fish
hatch shell
pip install -e '.[dev]'
cista --dev -l :8000 /path/to/files
```
We use `hatch shell` for installing on a virtual environment, to avoid disturbing the rest of the system with our hacking.
Vue is used to build files in `cista/wwwroot`, included prebuilt in the Python package. Running `hatch build` builds the frontend and creates a NodeJS-independent Python package.
## System Deployment
This setup allows easy addition of storages, each with its own domain, configuration, and files.
Assuming a restricted user account `storage` for serving files and that cista is installed system-wide or on this account (check with `sudo -u storage -s`). Alternatively, use `pipx run cista` or `hatch run cista` as the ExecStart command.
Create `/etc/systemd/system/cista@.service`:
```ini
[Unit]
Description=Cista storage %i
[Service]
User=storage
ExecStart=cista -c /srv/cista/%i -l /srv/cista/%i/socket /media/storage/%i
Restart=always
[Install]
WantedBy=multi-user.target
```
This setup supports multiple storages, each under `/media/storage/<domain>` for files and `/srv/cista/<domain>/` for configuration. UNIX sockets are used instead of numeric ports for convenience.
```fish
systemctl daemon-reload
systemctl enable --now cista@foo.example.com
systemctl enable --now cista@bar.example.com
```
Public exposure is easiest using the Caddy web server.
`/etc/caddy/Caddyfile`:
```Caddyfile
foo.example.com, bar.example.com {
reverse_proxy unix//srv/cista/{host}/socket
}
```

View File

@@ -62,15 +62,12 @@ def _main():
_confdir(args) _confdir(args)
exists = config.conffile.exists() exists = config.conffile.exists()
import_droppy = args["--import-droppy"] import_droppy = args["--import-droppy"]
necessary_opts = exists or import_droppy or path necessary_opts = exists or import_droppy or path and listen
if not necessary_opts: if not necessary_opts:
# Maybe run without arguments # Maybe run without arguments
print(doc) print(doc)
print( print(
"No config file found! Get started with one of:\n" "No config file found! Get started with:\n cista -l :8000 /path/to/files, or\n cista -l example.com --import-droppy # Uses Droppy files\n",
" cista --user yourname --privileged\n"
" cista --import-droppy\n"
" cista -l :8000 /path/to/files\n"
) )
return 1 return 1
settings = {} settings = {}
@@ -82,15 +79,8 @@ def _main():
settings = droppy.readconf() settings = droppy.readconf()
if path: if path:
settings["path"] = path settings["path"] = path
elif not exists:
settings["path"] = Path.home() / "Downloads"
if listen: if listen:
settings["listen"] = listen settings["listen"] = listen
elif not exists:
settings["listen"] = ":8000"
if not exists and not import_droppy:
# We have no users, so make it public
settings["public"] = True
operation = config.update_config(settings) operation = config.update_config(settings)
print(f"Config {operation}: {config.conffile}") print(f"Config {operation}: {config.conffile}")
# Prepare to serve # Prepare to serve
@@ -122,23 +112,11 @@ def _confdir(args):
def _user(args): def _user(args):
_confdir(args) _confdir(args)
if config.conffile.exists(): config.load_config()
config.load_config()
operation = False
else:
# Defaults for new config when user is created
operation = config.update_config(
{
"listen": ":8000",
"path": Path.home() / "Downloads",
"public": False,
}
)
print(f"Config {operation}: {config.conffile}\n")
name = args["--user"] name = args["--user"]
if not name or not name.isidentifier(): if not name or not name.isidentifier():
raise ValueError("Invalid username") raise ValueError("Invalid username")
config.load_config()
u = config.config.users.get(name) u = config.config.users.get(name)
info = f"User {name}" if u else f"New user {name}" info = f"User {name}" if u else f"New user {name}"
changes = {} changes = {}
@@ -150,17 +128,12 @@ def _user(args):
info += " (admin)" if oldadmin else "" info += " (admin)" if oldadmin else ""
if args["--password"] or not u: if args["--password"] or not u:
changes["password"] = pw = pwgen.generate() changes["password"] = pw = pwgen.generate()
info += f"\n Password: {pw}\n" info += f"\n Password: {pw}"
res = config.update_user(name, changes) res = config.update_user(args["--user"], changes)
print(info) print(info)
if res == "read": if res == "read":
print(" No changes") print(" No changes")
if operation == "created":
print(
"Now you can run the server:\n cista # defaults set: -l :8000 ~/Downloads\n"
)
if __name__ == "__main__": if __name__ == "__main__":
sys.exit(main()) sys.exit(main())

View File

@@ -37,23 +37,16 @@ async def upload(req, ws):
) )
req = msgspec.json.decode(text, type=FileRange) req = msgspec.json.decode(text, type=FileRange)
pos = req.start pos = req.start
while True: data = None
data = await ws.recv() while pos < req.end and (data := await ws.recv()) and isinstance(data, bytes):
if not isinstance(data, bytes):
break
if len(data) > req.end - pos:
raise ValueError(
f"Expected up to {req.end - pos} bytes, got {len(data)} bytes"
)
sentsize = await alink(("upload", req.name, pos, data, req.size)) sentsize = await alink(("upload", req.name, pos, data, req.size))
pos += typing.cast(int, sentsize) pos += typing.cast(int, sentsize)
if pos >= req.end:
break
if pos != req.end: if pos != req.end:
d = f"{len(data)} bytes" if isinstance(data, bytes) else data d = f"{len(data)} bytes" if isinstance(data, bytes) else data
raise ValueError(f"Expected {req.end - pos} more bytes, got {d}") raise ValueError(f"Expected {req.end - pos} more bytes, got {d}")
# Report success # Report success
res = StatusMsg(status="ack", req=req) res = StatusMsg(status="ack", req=req)
print("ack", res)
await asend(ws, res) await asend(ws, res)
@@ -111,24 +104,13 @@ async def watch(req, ws):
) )
uuid = token_bytes(16) uuid = token_bytes(16)
try: try:
q, space, root = await asyncio.get_event_loop().run_in_executor( with watching.state.lock:
req.app.ctx.threadexec, subscribe, uuid, ws q = watching.pubsub[uuid] = asyncio.Queue()
) # Init with disk usage and full tree
await ws.send(space) await ws.send(watching.format_space(watching.state.space))
await ws.send(root) await ws.send(watching.format_root(watching.state.root))
# Send updates # Send updates
while True: while True:
await ws.send(await q.get()) await ws.send(await q.get())
finally: finally:
del watching.pubsub[uuid] del watching.pubsub[uuid]
def subscribe(uuid, ws):
with watching.state.lock:
q = watching.pubsub[uuid] = asyncio.Queue()
# Init with disk usage and full tree
return (
q,
watching.format_space(watching.state.space),
watching.format_root(watching.state.root),
)

View File

@@ -1,7 +1,6 @@
import asyncio import asyncio
import datetime import datetime
import mimetypes import mimetypes
import threading
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from pathlib import Path, PurePath, PurePosixPath from pathlib import Path, PurePath, PurePosixPath
from stat import S_IFDIR, S_IFREG from stat import S_IFDIR, S_IFREG
@@ -12,11 +11,11 @@ import brotli
import sanic.helpers import sanic.helpers
from blake3 import blake3 from blake3 import blake3
from sanic import Blueprint, Sanic, empty, raw from sanic import Blueprint, Sanic, empty, raw
from sanic.exceptions import Forbidden, NotFound from sanic.exceptions import Forbidden, NotFound, ServerError
from sanic.log import logger from sanic.log import logging
from stream_zip import ZIP_AUTO, stream_zip from stream_zip import ZIP_AUTO, stream_zip
from cista import auth, config, preview, session, watching from cista import auth, config, session, watching
from cista.api import bp from cista.api import bp
from cista.util.apphelpers import handle_sanic_exception from cista.util.apphelpers import handle_sanic_exception
@@ -25,7 +24,6 @@ sanic.helpers._ENTITY_HEADERS = frozenset()
app = Sanic("cista", strict_slashes=True) app = Sanic("cista", strict_slashes=True)
app.blueprint(auth.bp) app.blueprint(auth.bp)
app.blueprint(preview.bp)
app.blueprint(bp) app.blueprint(bp)
app.exception(Exception)(handle_sanic_exception) app.exception(Exception)(handle_sanic_exception)
@@ -33,15 +31,14 @@ app.exception(Exception)(handle_sanic_exception)
@app.before_server_start @app.before_server_start
async def main_start(app, loop): async def main_start(app, loop):
config.load_config() config.load_config()
await watching.start(app, loop)
app.ctx.threadexec = ThreadPoolExecutor( app.ctx.threadexec = ThreadPoolExecutor(
max_workers=8, thread_name_prefix="cista-ioworker" max_workers=8, thread_name_prefix="cista-ioworker"
) )
await watching.start(app, loop)
@app.after_server_stop @app.after_server_stop
async def main_stop(app, loop): async def main_stop(app, loop):
quit.set()
await watching.stop(app, loop) await watching.stop(app, loop)
app.ctx.threadexec.shutdown() app.ctx.threadexec.shutdown()
@@ -123,19 +120,10 @@ def _load_wwwroot(www):
br = False br = False
wwwnew[name] = data, br, headers wwwnew[name] = data, br, headers
if not wwwnew: if not wwwnew:
msg = f"Web frontend missing from {base}\n Did you forget: hatch build\n" raise ServerError(
if not www: "Web frontend missing. Did you forget npm run build?",
logger.warning(msg) extra={"wwwroot": str(base)},
if not app.debug: quiet=True,
msg = "Web frontend missing. Cista installation is broken.\n"
wwwnew[""] = (
msg.encode(),
False,
{
"etag": "error",
"content-type": "text/plain",
"cache-control": "no-store",
},
) )
return wwwnew return wwwnew
@@ -144,7 +132,7 @@ def _load_wwwroot(www):
async def start(app): async def start(app):
await load_wwwroot(app) await load_wwwroot(app)
if app.debug: if app.debug:
app.add_task(refresh_wwwroot(), name="refresh_wwwroot") app.add_task(refresh_wwwroot())
async def load_wwwroot(app): async def load_wwwroot(app):
@@ -154,31 +142,27 @@ async def load_wwwroot(app):
) )
quit = threading.Event()
async def refresh_wwwroot(): async def refresh_wwwroot():
try: while True:
while not quit.is_set(): await asyncio.sleep(0.5)
try: try:
wwwold = www wwwold = www
await load_wwwroot(app) await load_wwwroot(app)
changes = "" changes = ""
for name in sorted(www): for name in sorted(www):
attr = www[name] attr = www[name]
if wwwold.get(name) == attr: if wwwold.get(name) == attr:
continue continue
headers = attr[2] headers = attr[2]
changes += f"{headers['last-modified']} {headers['etag']} /{name}\n" changes += f"{headers['last-modified']} {headers['etag']} /{name}\n"
for name in sorted(set(wwwold) - set(www)): for name in sorted(set(wwwold) - set(www)):
changes += f"Deleted /{name}\n" changes += f"Deleted /{name}\n"
if changes: if changes:
print(f"Updated wwwroot:\n{changes}", end="", flush=True) print(f"Updated wwwroot:\n{changes}", end="", flush=True)
except Exception as e: except Exception as e:
print(f"Error loading wwwroot: {e!r}") print("Error loading wwwroot", e)
await asyncio.sleep(0.5) if not app.debug:
except asyncio.CancelledError: return
pass
@app.route("/<path:path>", methods=["GET", "HEAD"]) @app.route("/<path:path>", methods=["GET", "HEAD"])
@@ -258,7 +242,7 @@ async def zip_download(req, keys, zipfile, ext):
for chunk in stream_zip(local_files(files)): for chunk in stream_zip(local_files(files)):
asyncio.run_coroutine_threadsafe(queue.put(chunk), loop).result() asyncio.run_coroutine_threadsafe(queue.put(chunk), loop).result()
except Exception: except Exception:
logger.exception("Error streaming ZIP") logging.exception("Error streaming ZIP")
raise raise
finally: finally:
asyncio.run_coroutine_threadsafe(queue.put(None), loop) asyncio.run_coroutine_threadsafe(queue.put(None), loop)

View File

@@ -71,7 +71,7 @@ def verify(request, *, privileged=False):
raise Forbidden("Access Forbidden: Only for privileged users", quiet=True) raise Forbidden("Access Forbidden: Only for privileged users", quiet=True)
elif config.config.public or request.ctx.user: elif config.config.public or request.ctx.user:
return return
raise Unauthorized(f"Login required for {request.path}", "cookie", quiet=True) raise Unauthorized("Login required", "cookie", quiet=True)
bp = Blueprint("auth") bp = Blueprint("auth")

View File

@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
import secrets import secrets
import sys
from functools import wraps from functools import wraps
from hashlib import sha256 from hashlib import sha256
from pathlib import Path, PurePath from pathlib import Path, PurePath
@@ -91,8 +90,6 @@ def config_update(modify):
return "read" return "read"
f.write(new) f.write(new)
f.close() f.close()
if sys.platform == "win32":
conffile.unlink() # Windows doesn't support atomic replace
tmpname.rename(conffile) # Atomic replace tmpname.rename(conffile) # Atomic replace
except: except:
f.close() f.close()
@@ -138,7 +135,7 @@ def update_user(conf: Config, name: str, changes: dict) -> Config:
# Encode into dict, update values with new, convert to Config # Encode into dict, update values with new, convert to Config
try: try:
u = conf.users[name].__copy__() u = conf.users[name].__copy__()
except (KeyError, AttributeError): except KeyError:
u = User() u = User()
if "password" in changes: if "password" in changes:
from . import auth from . import auth
@@ -147,7 +144,7 @@ def update_user(conf: Config, name: str, changes: dict) -> Config:
del changes["password"] del changes["password"]
udict = msgspec.to_builtins(u, enc_hook=enc_hook) udict = msgspec.to_builtins(u, enc_hook=enc_hook)
udict.update(changes) udict.update(changes)
settings = msgspec.to_builtins(conf, enc_hook=enc_hook) if conf else {"users": {}} settings = msgspec.to_builtins(conf, enc_hook=enc_hook)
settings["users"][name] = msgspec.convert(udict, User, dec_hook=dec_hook) settings["users"][name] = msgspec.convert(udict, User, dec_hook=dec_hook)
return msgspec.convert(settings, Config, dec_hook=dec_hook) return msgspec.convert(settings, Config, dec_hook=dec_hook)

View File

@@ -34,11 +34,9 @@ class File:
self.open_rw() self.open_rw()
assert self.fd is not None assert self.fd is not None
if file_size is not None: if file_size is not None:
assert pos + len(buffer) <= file_size
os.ftruncate(self.fd, file_size) os.ftruncate(self.fd, file_size)
if buffer: os.lseek(self.fd, pos, os.SEEK_SET)
os.lseek(self.fd, pos, os.SEEK_SET) os.write(self.fd, buffer)
os.write(self.fd, buffer)
def __getitem__(self, slice): def __getitem__(self, slice):
if self.fd is None: if self.fd is None:

View File

@@ -1,52 +0,0 @@
import asyncio
import io
from pathlib import PurePosixPath
from urllib.parse import unquote
from PIL import Image
from sanic import Blueprint, raw
from sanic.exceptions import Forbidden, NotFound
from sanic.log import logger
from cista import config
from cista.util.filename import sanitize
bp = Blueprint("preview", url_prefix="/preview")
@bp.get("/<path:path>")
async def preview(req, path):
"""Preview a file"""
width = int(req.query_string) if req.query_string else 1024
rel = PurePosixPath(sanitize(unquote(path)))
path = config.config.path / rel
if not path.is_file():
raise NotFound("File not found")
size = path.lstat().st_size
if size > 20 * 10**6:
raise Forbidden("File too large")
img = await asyncio.get_event_loop().run_in_executor(
req.app.ctx.threadexec, process_image, path, width
)
return raw(img, content_type="image/webp")
def process_image(path, maxsize):
img = Image.open(path)
w, h = img.size
img.thumbnail((min(w, maxsize), min(h, maxsize)))
# Fix rotation based on EXIF data
try:
rotate_values = {3: 180, 6: 270, 8: 90}
exif = img._getexif()
if exif:
orientation = exif.get(274)
if orientation in rotate_values:
logger.debug(f"Rotating preview {path} by {rotate_values[orientation]}")
img = img.rotate(rotate_values[orientation], expand=True)
except Exception as e:
logger.error(f"Error rotating preview image: {e}")
# Save as webp
imgdata = io.BytesIO()
img.save(imgdata, format="webp", quality=70, method=6)
return imgdata.getvalue()

View File

@@ -120,9 +120,6 @@ class FileEntry(msgspec.Struct, array_like=True):
size: int size: int
isfile: int isfile: int
def __repr__(self):
return self.key or "FileEntry()"
class Update(msgspec.Struct, array_like=True): class Update(msgspec.Struct, array_like=True):
... ...
@@ -140,12 +137,20 @@ class UpdIns(Update, tag="i"):
items: list[FileEntry] items: list[FileEntry]
class UpdateMessage(msgspec.Struct):
update: list[UpdKeep | UpdDel | UpdIns]
class Space(msgspec.Struct): class Space(msgspec.Struct):
disk: int disk: int
free: int free: int
usage: int usage: int
storage: int storage: int
def make_dir_data(root):
if len(root) == 3:
return FileEntry(*root)
id_, size, mtime, listing = root
converted = {}
for name, data in listing.items():
converted[name] = make_dir_data(data)
sz = sum(x.size for x in converted.values())
mt = max(x.mtime for x in converted.values())
return DirEntry(id_, sz, max(mt, mtime), converted)

View File

@@ -1,6 +1,6 @@
import os import os
import re import re
from pathlib import Path from pathlib import Path, PurePath
from sanic import Sanic from sanic import Sanic
@@ -15,6 +15,7 @@ def run(*, dev=False):
# Silence Sanic's warning about running in production rather than debug # Silence Sanic's warning about running in production rather than debug
os.environ["SANIC_IGNORE_PRODUCTION_WARNING"] = "1" os.environ["SANIC_IGNORE_PRODUCTION_WARNING"] = "1"
confdir = config.conffile.parent confdir = config.conffile.parent
wwwroot = PurePath(__file__).parent / "wwwroot"
if opts.get("ssl"): if opts.get("ssl"):
# Run plain HTTP redirect/acme server on port 80 # Run plain HTTP redirect/acme server on port 80
server80.app.prepare(port=80, motd=False) server80.app.prepare(port=80, motd=False)
@@ -26,7 +27,7 @@ def run(*, dev=False):
motd=False, motd=False,
dev=dev, dev=dev,
auto_reload=dev, auto_reload=dev,
reload_dir={confdir}, reload_dir={confdir, wwwroot},
access_log=True, access_log=True,
) # type: ignore ) # type: ignore
if dev: if dev:
@@ -51,7 +52,7 @@ def parse_listen(listen):
raise ValueError( raise ValueError(
f"Directory for unix socket does not exist: {unix.parent}/", f"Directory for unix socket does not exist: {unix.parent}/",
) )
return "http://localhost", {"unix": unix.as_posix()} return "http://localhost", {"unix": unix}
if re.fullmatch(r"(\w+(-\w+)*\.)+\w{2,}", listen, re.UNICODE): if re.fullmatch(r"(\w+(-\w+)*\.)+\w{2,}", listen, re.UNICODE):
return f"https://{listen}", {"host": listen, "port": 443, "ssl": True} return f"https://{listen}", {"host": listen, "port": 443, "ssl": True}
try: try:

View File

@@ -21,6 +21,7 @@ def jres(data, **kwargs):
async def handle_sanic_exception(request, e): async def handle_sanic_exception(request, e):
logger.exception(e)
context, code = {}, 500 context, code = {}, 500
message = str(e) message = str(e)
if isinstance(e, SanicException): if isinstance(e, SanicException):
@@ -41,7 +42,7 @@ async def handle_sanic_exception(request, e):
res.cookies.add_cookie("message", message, max_age=5) res.cookies.add_cookie("message", message, max_age=5)
return res return res
# Otherwise use Sanic's default error page # Otherwise use Sanic's default error page
return errorpages.HTMLRenderer(request, e, debug=request.app.debug).render() return errorpages.HTMLRenderer(request, e, debug=request.app.debug).full()
def websocket_wrapper(handler): def websocket_wrapper(handler):
@@ -53,14 +54,13 @@ def websocket_wrapper(handler):
auth.verify(request) auth.verify(request)
await handler(request, ws, *args, **kwargs) await handler(request, ws, *args, **kwargs)
except Exception as e: except Exception as e:
logger.exception(e)
context, code, message = {}, 500, str(e) or "Internal Server Error" context, code, message = {}, 500, str(e) or "Internal Server Error"
if isinstance(e, SanicException): if isinstance(e, SanicException):
context = e.context or {} context = e.context or {}
code = e.status_code code = e.status_code
message = f"⚠️ {message}" if code < 500 else f"🛑 {message}" message = f"⚠️ {message}" if code < 500 else f"🛑 {message}"
await asend(ws, ErrorMsg({"code": code, "message": message, **context})) await asend(ws, ErrorMsg({"code": code, "message": message, **context}))
if not getattr(e, "quiet", False):
logger.exception(f"{code} {e!r}")
raise raise
return wrapper return wrapper

View File

@@ -1,16 +1,15 @@
import asyncio import asyncio
import shutil import shutil
import stat
import sys import sys
import threading import threading
import time import time
from contextlib import suppress
from os import stat_result from os import stat_result
from pathlib import Path, PurePosixPath from pathlib import Path, PurePosixPath
from stat import S_ISDIR, S_ISREG
import msgspec import msgspec
from natsort import humansorted, natsort_keygen, ns from natsort import humansorted, natsort_keygen, ns
from sanic.log import logger from sanic.log import logging
from cista import config from cista import config
from cista.fileio import fuid from cista.fileio import fuid
@@ -51,42 +50,37 @@ class State:
begin, end = 0, len(self._listing) begin, end = 0, len(self._listing)
level = 0 level = 0
isfile = 0 isfile = 0
while level < len(relpath.parts):
# Special case for root # Enter a subdirectory
if not relpath.parts:
return slice(begin, end)
begin += 1
for part in relpath.parts:
level += 1 level += 1
found = False begin += 1
if level == len(relpath.parts):
while begin < end: isfile = relfile
entry = self._listing[begin] name = relpath.parts[level - 1]
namesort = sortkey(name)
if entry.level < level: r = self._listing[begin]
break assert r.level == level
# Iterate over items at this level
if entry.level == level: while (
if entry.name == part: begin < end
found = True and r.name != name
if level == len(relpath.parts): and r.isfile <= isfile
isfile = relfile and sortkey(r.name) < namesort
else: ):
begin += 1 # Skip contents
break
cmp = entry.isfile - isfile or sortkey(entry.name) > sortkey(part)
if cmp > 0:
break
begin += 1 begin += 1
while begin < end and self._listing[begin].level > level:
if not found: begin += 1
# Not found?
if begin == end or self._listing[begin].level < level:
return slice(begin, begin)
r = self._listing[begin]
# Not found?
if begin == end or r.name != name:
return slice(begin, begin) return slice(begin, begin)
# Found an item, now find its end
# Found the starting point, now find the end of the slice for end in range(begin + 1, len(self._listing)):
for end in range(begin + 1, len(self._listing) + 1): if self._listing[end].level <= level:
if end == len(self._listing) or self._listing[end].level <= level:
break break
return slice(begin, end) return slice(begin, end)
@@ -111,73 +105,154 @@ class State:
with self.lock: with self.lock:
del self._listing[self._slice(relpath)] del self._listing[self._slice(relpath)]
def _index(self, rel: PurePosixPath):
idx = 0
ret = []
def _dir(self, idx: int):
level = self._listing[idx].level + 1
end = len(self._listing)
idx += 1
ret = []
while idx < end and (r := self._listing[idx]).level >= level:
if r.level == level:
ret.append(idx)
return ret, idx
def update(self, rel: PurePosixPath, value: FileEntry):
begin = 0
parents = []
while self._listing[begin].level < len(rel.parts):
parents.append(begin)
state = State() state = State()
rootpath: Path = None # type: ignore rootpath: Path = None # type: ignore
quit = threading.Event() quit = False
modified_flags = (
## Filesystem scanning "IN_CREATE",
"IN_DELETE",
"IN_DELETE_SELF",
"IN_MODIFY",
"IN_MOVE_SELF",
"IN_MOVED_FROM",
"IN_MOVED_TO",
)
def walk(rel: PurePosixPath, stat: stat_result | None = None) -> list[FileEntry]: def watcher_thread(loop):
global rootpath
import inotify.adapters
while True:
rootpath = config.config.path
i = inotify.adapters.InotifyTree(rootpath.as_posix())
# Initialize the tree from filesystem
old, new = state.root, walk()
if old != new:
with state.lock:
state.root = new
broadcast(format_root(new), loop)
# The watching is not entirely reliable, so do a full refresh every minute
refreshdl = time.monotonic() + 60.0
for event in i.event_gen():
if quit:
return
# Disk usage update
du = shutil.disk_usage(rootpath)
space = Space(*du, storage=state.root[0].size)
if space != state.space:
state.space = space
broadcast(format_space(space), loop)
break
# Do a full refresh?
if time.monotonic() > refreshdl:
break
if event is None:
continue
_, flags, path, filename = event
if not any(f in modified_flags for f in flags):
continue
# Update modified path
path = PurePosixPath(path) / filename
try:
update(path.relative_to(rootpath), loop)
except Exception as e:
print("Watching error", e, path, rootpath)
raise
i = None # Free the inotify object
def watcher_thread_poll(loop):
global rootpath
while not quit:
rootpath = config.config.path
old = state.root
new = walk()
if old != new:
with state.lock:
state.root = new
broadcast(format_update(old, new), loop)
# Disk usage update
du = shutil.disk_usage(rootpath)
space = Space(*du, storage=state.root[0].size)
if space != state.space:
state.space = space
broadcast(format_space(space), loop)
time.sleep(2.0)
def walk(rel=PurePosixPath()) -> list[FileEntry]: # noqa: B008
path = rootpath / rel
try:
st = path.stat()
except OSError:
return []
return _walk(rel, int(not stat.S_ISDIR(st.st_mode)), st)
def _walk(rel: PurePosixPath, isfile: int, st: stat_result) -> list[FileEntry]:
entry = FileEntry(
level=len(rel.parts),
name=rel.name,
key=fuid(st),
mtime=int(st.st_mtime),
size=st.st_size if isfile else 0,
isfile=isfile,
)
if isfile:
return [entry]
ret = [entry]
path = rootpath / rel path = rootpath / rel
ret = []
try: try:
st = stat or path.stat()
isfile = not S_ISDIR(st.st_mode)
entry = FileEntry(
level=len(rel.parts),
name=rel.name,
key=fuid(st),
mtime=int(st.st_mtime),
size=st.st_size if isfile else 0,
isfile=isfile,
)
if isfile:
return [entry]
# Walk all entries of the directory
ret = [entry]
li = [] li = []
for f in path.iterdir(): for f in path.iterdir():
if quit.is_set():
raise SystemExit("quit")
if f.name.startswith("."): if f.name.startswith("."):
continue # No dotfiles continue # No dotfiles
with suppress(FileNotFoundError): s = f.stat()
s = f.lstat() li.append((int(not stat.S_ISDIR(s.st_mode)), f.name, s))
isfile = S_ISREG(s.st_mode) for [isfile, name, s] in humansorted(li):
isdir = S_ISDIR(s.st_mode) subtree = _walk(rel / name, isfile, s)
if not isfile and not isdir: child = subtree[0]
continue
li.append((int(isfile), f.name, s))
# Build the tree as a list of FileEntries
for [_, name, s] in humansorted(li):
sub = walk(rel / name, stat=s)
ret.extend(sub)
child = sub[0]
entry.mtime = max(entry.mtime, child.mtime) entry.mtime = max(entry.mtime, child.mtime)
entry.size += child.size entry.size += child.size
ret.extend(subtree)
except FileNotFoundError: except FileNotFoundError:
pass # Things may be rapidly in motion pass # Things may be rapidly in motion
except OSError as e: except OSError as e:
if e.errno == 13: # Permission denied print("OS error walking path", path, e)
pass
logger.error(f"Watching {path=}: {e!r}")
return ret return ret
def update_root(loop): def update(relpath: PurePosixPath, loop):
"""Full filesystem scan""" """Called by inotify updates, check the filesystem and broadcast any changes."""
new = walk(PurePosixPath()) if rootpath is None or relpath is None:
with state.lock: print("ERROR", rootpath, relpath)
old = state.root
if old != new:
state.root = new
broadcast(format_update(old, new), loop)
def update_path(relpath: PurePosixPath, loop):
"""Called on FS updates, check the filesystem and broadcast any changes."""
new = walk(relpath) new = walk(relpath)
with state.lock: with state.lock:
old = state[relpath] old = state[relpath]
@@ -191,22 +266,6 @@ def update_path(relpath: PurePosixPath, loop):
broadcast(format_update(old, state.root), loop) broadcast(format_update(old, state.root), loop)
def update_space(loop):
"""Called periodically to update the disk usage."""
du = shutil.disk_usage(rootpath)
space = Space(*du, storage=state.root[0].size)
# Update only on difference above 1 MB
tol = 10**6
old = msgspec.structs.astuple(state.space)
new = msgspec.structs.astuple(space)
if any(abs(o - n) > tol for o, n in zip(old, new, strict=True)):
state.space = space
broadcast(format_space(space), loop)
## Messaging
def format_update(old, new): def format_update(old, new):
# Make keep/del/insert diff until one of the lists ends # Make keep/del/insert diff until one of the lists ends
oidx, nidx = 0, 0 oidx, nidx = 0, 0
@@ -224,11 +283,13 @@ def format_update(old, new):
del_count = 0 del_count = 0
rest = new[nidx:] rest = new[nidx:]
while oidx < len(old) and old[oidx] not in rest: while old[oidx] not in rest:
del_count += 1 del_count += 1
oidx += 1 oidx += 1
if del_count: if del_count:
update.append(UpdDel(del_count)) update.append(UpdDel(del_count))
oidx += 1
continue continue
insert_items = [] insert_items = []
@@ -267,77 +328,19 @@ async def abroadcast(msg):
queue.put_nowait(msg) queue.put_nowait(msg)
except Exception: except Exception:
# Log because asyncio would silently eat the error # Log because asyncio would silently eat the error
logger.exception("Broadcast error") logging.exception("Broadcast error")
## Watcher thread
def watcher_inotify(loop):
"""Inotify watcher thread (Linux only)"""
import inotify.adapters
modified_flags = (
"IN_CREATE",
"IN_DELETE",
"IN_DELETE_SELF",
"IN_MODIFY",
"IN_MOVE_SELF",
"IN_MOVED_FROM",
"IN_MOVED_TO",
)
while not quit.is_set():
i = inotify.adapters.InotifyTree(rootpath.as_posix())
# Initialize the tree from filesystem
update_root(loop)
trefresh = time.monotonic() + 30.0
tspace = time.monotonic() + 5.0
# Watch for changes (frequent wakeups needed for quiting)
for event in i.event_gen(timeout_s=0.1):
if quit.is_set():
break
t = time.monotonic()
# The watching is not entirely reliable, so do a full refresh every 30 seconds
if t >= trefresh:
break
# Disk usage update
if t >= tspace:
tspace = time.monotonic() + 5.0
update_space(loop)
# Inotify event, update the tree
if event and any(f in modified_flags for f in event[1]):
# Update modified path
update_path(PurePosixPath(event[2]) / event[3], loop)
del i # Free the inotify object
def watcher_poll(loop):
"""Polling version of the watcher thread."""
while not quit.is_set():
t0 = time.perf_counter()
update_root(loop)
update_space(loop)
dur = time.perf_counter() - t0
if dur > 1.0:
logger.debug(f"Reading the full file list took {dur:.1f}s")
quit.wait(0.1 + 8 * dur)
async def start(app, loop): async def start(app, loop):
global rootpath
config.load_config() config.load_config()
rootpath = config.config.path
use_inotify = sys.platform == "linux"
app.ctx.watcher = threading.Thread( app.ctx.watcher = threading.Thread(
target=watcher_inotify if use_inotify else watcher_poll, target=watcher_thread if sys.platform == "linux" else watcher_thread_poll,
args=[loop], args=[loop],
# Descriptive name for system monitoring
name=f"cista-watcher {rootpath}",
) )
app.ctx.watcher.start() app.ctx.watcher.start()
async def stop(app, loop): async def stop(app, loop):
quit.set() global quit
quit = True
app.ctx.watcher.join() app.ctx.watcher.join()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 363 KiB

View File

@@ -1,46 +1,40 @@
# Cista Vue Frontend # cista-front
The frontend is a Single-Page App implemented with Vue 3. Development uses the Vite server together with the main Python backend, but in production the latter also serves the prebuilt frontend files. This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup ## Recommended IDE Setup
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin). [VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
## Type Support for `.vue` Imports in TS ## Type Support for `.vue` Imports in TS
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types. TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types.
If the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps: If the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps:
1. Disable the built-in TypeScript Extension 1. Disable the built-in TypeScript Extension
1) Run `Extensions: Show Built-in Extensions` from VSCode's command palette 1) Run `Extensions: Show Built-in Extensions` from VSCode's command palette
2) Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)` 2) Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)`
2. Reload the VSCode window by running `Developer: Reload Window` from the command palette. 2. Reload the VSCode window by running `Developer: Reload Window` from the command palette.
## Hot-Reload for Development ## Customize configuration
### Run the backend See [Vite Configuration Reference](https://vitejs.dev/config/).
```fish ## Project Setup
hatch shell
cista --dev -l :8000 ```sh
``` npm install
```
### And the Vite server (in another terminal)
### Compile and Hot-Reload for Development
```fish
cd frontend ```sh
npm install npm run dev
npm run dev ```
```
Browse to Vite, which will proxy API requests to port 8000. Both servers live reload changes. ### Type-Check, Compile and Minify for Production
```sh
### Type-Check, Compile and Minify for Production npm run build
```
This is also called by `hatch build` during Python packaging:
```fish
npm run build
```

View File

@@ -4,7 +4,7 @@
<HeaderMain ref="headerMain" :path="path.pathList" :query="path.query"> <HeaderMain ref="headerMain" :path="path.pathList" :query="path.query">
<HeaderSelected :path="path.pathList" /> <HeaderSelected :path="path.pathList" />
</HeaderMain> </HeaderMain>
<BreadCrumb :path="path.pathList" primary /> <BreadCrumb :path="path.pathList" tabindex="-1"/>
</header> </header>
<main> <main>
<RouterView :path="path.pathList" :query="path.query" /> <RouterView :path="path.pathList" :query="path.query" />
@@ -17,18 +17,17 @@ import type { ComputedRef } from 'vue'
import type HeaderMain from '@/components/HeaderMain.vue' import type HeaderMain from '@/components/HeaderMain.vue'
import { onMounted, onUnmounted, ref, watchEffect } from 'vue' import { onMounted, onUnmounted, ref, watchEffect } from 'vue'
import { loadSession, watchConnect, watchDisconnect } from '@/repositories/WS' import { loadSession, watchConnect, watchDisconnect } from '@/repositories/WS'
import { useMainStore } from '@/stores/main' import { useDocumentStore } from '@/stores/documents'
import { computed } from 'vue' import { computed } from 'vue'
import Router from '@/router/index' import Router from '@/router/index'
import type { SortOrder } from './utils/docsort'
interface Path { interface Path {
path: string path: string
pathList: string[] pathList: string[]
query: string query: string
} }
const store = useMainStore() const documentStore = useDocumentStore()
const path: ComputedRef<Path> = computed(() => { const path: ComputedRef<Path> = computed(() => {
const p = decodeURIComponent(Router.currentRoute.value.path).split('//') const p = decodeURIComponent(Router.currentRoute.value.path).split('//')
const pathList = p[0].split('/').filter(value => value !== '') const pathList = p[0].split('/').filter(value => value !== '')
@@ -40,68 +39,50 @@ const path: ComputedRef<Path> = computed(() => {
} }
}) })
watchEffect(() => { watchEffect(() => {
document.title = path.value.path.replace(/\/$/, '').split('/').pop() || store.server.name || 'Cista Storage' document.title = path.value.path.replace(/\/$/, '').split('/').pop() || documentStore.server.name || 'Cista Storage'
}) })
onMounted(loadSession) onMounted(loadSession)
onMounted(watchConnect) onMounted(watchConnect)
onUnmounted(watchDisconnect) onUnmounted(watchDisconnect)
// Update human-readable x seconds ago messages from mtimes
setInterval(documentStore.updateModified, 1000)
const headerMain = ref<typeof HeaderMain | null>(null) const headerMain = ref<typeof HeaderMain | null>(null)
let vert = 0 let vert = 0
let timer: any = null let timer: any = null
const globalShortcutHandler = (event: KeyboardEvent) => { const globalShortcutHandler = (event: KeyboardEvent) => {
const fileExplorer = store.fileExplorer as any const fileExplorer = documentStore.fileExplorer as any
if (!fileExplorer) return if (!fileExplorer) return
const c = fileExplorer.isCursor() const c = fileExplorer.isCursor()
const input = (event.target as HTMLElement).tagName === 'INPUT'
const keyup = event.type === 'keyup' const keyup = event.type === 'keyup'
if (event.repeat) { if (event.repeat) {
if ( if (
event.key === 'ArrowUp' || event.key === 'ArrowUp' ||
event.key === 'ArrowDown' || event.key === 'ArrowDown' ||
event.key === 'ArrowLeft' ||
event.key === 'ArrowRight' ||
(c && event.code === 'Space') (c && event.code === 'Space')
) { ) {
if (!input) event.preventDefault() event.preventDefault()
} }
return return
} }
//console.log("key pressed", event) //console.log("key pressed", event)
/// Long if-else machina for all keys we handle here // For up/down implement custom fast repeat
let arrow = '' if (event.key === 'ArrowUp') vert = keyup ? 0 : event.altKey ? -10 : -1
if (event.key.startsWith("Arrow")) arrow = event.key.slice(5).toLowerCase() else if (event.key === 'ArrowDown') vert = keyup ? 0 : event.altKey ? 10 : 1
// Find: process on keydown so that we can bypass the built-in search hotkey // Find: process on keydown so that we can bypass the built-in search hotkey
else if (!keyup && event.key === 'f' && (event.ctrlKey || event.metaKey)) { else if (!keyup && event.key === 'f' && (event.ctrlKey || event.metaKey)) {
headerMain.value!.toggleSearchInput() headerMain.value!.toggleSearchInput()
} }
// Search also on / (UNIX style) // Select all (toggle); keydown to prevent builtin
else if (keyup && !input && event.key === '/') {
headerMain.value!.toggleSearchInput()
}
// Globally close search, clear errors on Escape
else if (keyup && event.key === 'Escape') {
store.error = ''
headerMain.value!.closeSearch(event)
store.focusBreadcrumb()
}
else if (!input && keyup && event.key === 'Backspace') {
Router.back()
}
// Select all (toggle); keydown to precede and prevent builtin
else if (!keyup && event.key === 'a' && (event.ctrlKey || event.metaKey)) { else if (!keyup && event.key === 'a' && (event.ctrlKey || event.metaKey)) {
fileExplorer.toggleSelectAll() fileExplorer.toggleSelectAll()
} }
// G toggles Gallery // Keys 1-3 to sort columns
else if (!input && keyup && event.key === 'g') {
store.prefs.gallery = !store.prefs.gallery
}
// Keys Backquote-1-2-3 to sort columns
else if ( else if (
!input && c &&
keyup && keyup &&
(event.code === 'Backquote' || event.key === '1' || event.key === '2' || event.key === '3') (event.key === '1' || event.key === '2' || event.key === '3')
) { ) {
store.sort(['', 'name', 'modified', 'size'][+event.key || 0] as SortOrder) fileExplorer.toggleSortColumn(+event.key)
} }
// Rename // Rename
else if (c && keyup && !event.ctrlKey && (event.key === 'F2' || event.key === 'r')) { else if (c && keyup && !event.ctrlKey && (event.key === 'F2' || event.key === 'r')) {
@@ -111,26 +92,28 @@ const globalShortcutHandler = (event: KeyboardEvent) => {
else if (c && event.code === 'Space') { else if (c && event.code === 'Space') {
if (keyup && !event.altKey && !event.ctrlKey) if (keyup && !event.altKey && !event.ctrlKey)
fileExplorer.cursorSelect() fileExplorer.cursorSelect()
} } else return
else return
/// We are handling this!
event.preventDefault() event.preventDefault()
if (timer) { if (!vert) {
clearTimeout(timer) // Good for either timeout or interval if (timer) {
timer = null clearTimeout(timer) // Good for either timeout or interval
timer = null
}
return
} }
let f: any if (!timer) {
switch (arrow) {
case 'up': f = () => fileExplorer.up(event); break
case 'down': f = () => fileExplorer.down(event); break
case 'left': f = () => fileExplorer.left(event); break
case 'right': f = () => fileExplorer.right(event); break
}
if (f && !keyup) {
// Initial move, then t0 delay until repeats at tr intervals // Initial move, then t0 delay until repeats at tr intervals
const t0 = 200, tr = event.altKey ? 20 : 100 const select = event.shiftKey
f() fileExplorer.cursorMove(vert, select)
timer = setTimeout(() => { timer = setInterval(f, tr) }, t0 - tr) const t0 = 200,
tr = 30
timer = setTimeout(
() =>
(timer = setInterval(() => {
fileExplorer.cursorMove(vert, select)
}, tr)),
t0 - tr
)
} }
} }
onMounted(() => { onMounted(() => {

View File

@@ -14,7 +14,7 @@
/* The following are overridden by responsive layouts */ /* The following are overridden by responsive layouts */
--root-font-size: 1rem; --root-font-size: 1rem;
--header-font-size: 1rem; --header-font-size: 1rem;
--header-height: 4rem; --header-height: calc(6.5 * var(--header-font-size));
} }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
:root { :root {
@@ -37,6 +37,12 @@
:root { :root {
--root-font-size: calc(8px + 8 * 100vw / 1000); --root-font-size: calc(8px + 8 * 100vw / 1000);
} }
header .buttons:has(input[type='search']) > div {
display: none;
}
header .buttons > div:has(input[type='search']) {
display: inherit;
}
} }
@media screen and (min-width: 2000px) { @media screen and (min-width: 2000px) {
:root { :root {
@@ -48,7 +54,6 @@
:root { :root {
--header-font-size: calc(10px + 10 * 100vh / 600); /* 20px at 600px height */ --header-font-size: calc(10px + 10 * 100vh / 600); /* 20px at 600px height */
--root-font-size: 0.8rem; --root-font-size: 0.8rem;
--header-height: 2rem;
} }
header .breadcrumb > * { header .breadcrumb > * {
padding-top: calc(8 + 8 * 100vh / 600) !important; padding-top: calc(8 + 8 * 100vh / 600) !important;
@@ -73,13 +78,17 @@
} }
header { header {
display: flex; display: flex;
flex-direction: row-reverse;
justify-content: space-between; justify-content: space-between;
align-items: end;
} }
header .headermain { order: 1; } header .breadcrumb {
header .breadcrumb { align-self: stretch; } flex-shrink: 1;
header .action-button { }
width: 2em; header .breadcrumb > * {
height: 2em; flex-shrink: 1;
padding-top: 1rem !important;
padding-bottom: 1rem !important;
} }
} }
@media print { @media print {
@@ -92,7 +101,7 @@
nav, nav,
.menu, .menu,
.rename-button { .rename-button {
display: none !important; display: none;
} }
.breadcrumb > a { .breadcrumb > a {
color: black !important; color: black !important;
@@ -113,7 +122,6 @@
padding-bottom: 0 !important; padding-bottom: 0 !important;
} }
thead tr { thead tr {
font-size: 1rem !important;
position: static !important; position: static !important;
background: none !important; background: none !important;
border-bottom: 1pt solid black !important; border-bottom: 1pt solid black !important;
@@ -134,9 +142,6 @@
left: 0; left: 0;
} }
} }
* {
box-sizing: border-box;
}
html { html {
font-size: var(--root-font-size); font-size: var(--root-font-size);
overflow: hidden; overflow: hidden;

View File

@@ -2,18 +2,14 @@
<nav <nav
class="breadcrumb" class="breadcrumb"
aria-label="Breadcrumb" aria-label="Breadcrumb"
@keydown.left.stop="move(-1)" @keyup.left.stop="move(-1)"
@keydown.right.stop="move(1)" @keyup.right.stop="move(1)"
@keyup.enter="move(0)" @focus="move(0)"
@focus=focusCurrent
tabindex=0
> >
<a href="#/" <a href="#/"
:ref="el => setLinkRef(0, el)" :ref="el => setLinkRef(0, el)"
:class="{ current: !!isCurrent(0) }" :class="{ current: !!isCurrent(0) }"
:aria-current="isCurrent(0)" :aria-current="isCurrent(0)"
@click.prevent="navigate(0)"
title="/"
> >
<component :is="home" /> <component :is="home" />
</a> </a>
@@ -23,7 +19,6 @@
:aria-current="isCurrent(index + 1)" :aria-current="isCurrent(index + 1)"
@click.prevent="navigate(index + 1)" @click.prevent="navigate(index + 1)"
:ref="el => setLinkRef(index + 1, el)" :ref="el => setLinkRef(index + 1, el)"
:title="`/${longest.slice(0, index + 1).join('/')}`"
>{{ location }}</a> >{{ location }}</a>
</template> </template>
</nav> </nav>
@@ -31,7 +26,7 @@
<script setup lang="ts"> <script setup lang="ts">
import home from '@/assets/svg/home.svg' import home from '@/assets/svg/home.svg'
import { nextTick, onBeforeUpdate, ref, watchEffect } from 'vue' import { onBeforeUpdate, ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
const router = useRouter() const router = useRouter()
@@ -42,33 +37,20 @@ onBeforeUpdate(() => { links.length = 1 }) // 1 to keep home
const props = defineProps<{ const props = defineProps<{
path: Array<string> path: Array<string>
primary?: boolean
}>() }>()
const longest = ref<Array<string>>([]) const longest = ref<Array<string>>([])
const isCurrent = (index: number) => index == props.path.length ? 'location' : undefined const isCurrent = (index: number) => index == props.path.length ? 'location' : undefined
const focusCurrent = () => {
nextTick(() => {
const index = props.path.length
if (index < links.length) links[index].focus()
})
}
const navigate = (index: number) => { const navigate = (index: number) => {
const link = links[index] const link = links[index]
if (!link) throw Error(`No link at index ${index} (path: ${props.path})`) if (!link) throw Error(`No link at index ${index} (path: ${props.path})`)
const url = index ? `/${longest.value.slice(0, index).join('/')}/` : '/' const url = `/${longest.value.slice(0, index).join('/')}/`
const long = longest.value.length ? `/${longest.value.join('/')}/` : '/' const here = `/${longest.value.join('/')}/`
const browser = decodeURIComponent(location.hash.slice(1).split('//')[0]) link.focus()
const u = url.replaceAll('?', '%3F').replaceAll('#', '%23') if (here.startsWith(location.hash.slice(1))) router.replace(url)
// Clicking on current link clears the rest of the path and adds new history else router.push(url)
if (isCurrent(index)) { longest.value.splice(index); router.push(u) }
// Moving along breadcrumbs doesn't create new history
else if (long.startsWith(browser)) router.replace(u)
// Nornal navigation from elsewhere (e.g. search result breadcrumbs)
else router.push(u)
} }
const move = (dir: number) => { const move = (dir: number) => {
@@ -80,16 +62,13 @@ const move = (dir: number) => {
watchEffect(() => { watchEffect(() => {
const longcut = longest.value.slice(0, props.path.length) const longcut = longest.value.slice(0, props.path.length)
const same = longcut.every((value, index) => value === props.path[index]) const same = longcut.every((value, index) => value === props.path[index])
// Navigated out of previous path, reset longest to current
if (!same) longest.value = props.path if (!same) longest.value = props.path
else if (props.path.length > longcut.length) { else if (props.path.length > longcut.length) {
longest.value = longcut.concat(props.path.slice(longcut.length)) longest.value = longcut.concat(props.path.slice(longcut.length))
} }
// If needed, focus primary navigation to new location })
if (props.primary) nextTick(() => { watchEffect(() => {
const act = document.activeElement as HTMLElement if (links.length) navigate(props.path.length)
if (!act || [...links, document.body].includes(act)) focusCurrent()
})
}) })
</script> </script>
@@ -104,35 +83,31 @@ watchEffect(() => {
--breadcrumb-transtime: 0.3s; --breadcrumb-transtime: 0.3s;
} }
.breadcrumb { .breadcrumb {
flex: 1 1 auto;
display: flex; display: flex;
min-width: 20%; list-style: none;
max-width: 100%;
min-height: 2em;
margin: 0; margin: 0;
padding: 0 1em 0 0; padding: 0 1em 0 0;
} }
.breadcrumb > a { .breadcrumb > a {
flex: 0 4 auto;
display: flex;
align-items: center;
margin: 0 -0.5em 0 -0.5em; margin: 0 -0.5em 0 -0.5em;
padding: 0; padding: 0;
max-width: 8em;
white-space: nowrap; white-space: nowrap;
text-overflow: ellipsis; text-overflow: ellipsis;
overflow: hidden; overflow: hidden;
height: 1.5em;
color: var(--breadcrumb-color); color: var(--breadcrumb-color);
padding: 0.3em 1.5em; padding: 0.3em 1.5em;
clip-path: polygon(0 0, 1em 50%, 0 100%, 100% 100%, 100% 0, 0 0); clip-path: polygon(0 0, 1em 50%, 0 100%, 100% 100%, 100% 0, 0 0);
transition: all var(--breadcrumb-transtime); transition: all var(--breadcrumb-transtime);
} }
.breadcrumb > a:first-child { .breadcrumb a:first-child {
flex: 0 0 auto; margin-left: 0;
padding-left: 1.5em; padding-left: .2em;
padding-right: 1.7em;
clip-path: none; clip-path: none;
} }
.breadcrumb > a:last-child { .breadcrumb a:last-child {
max-width: none;
clip-path: polygon( clip-path: polygon(
0 0, 0 0,
calc(100% - 1em) 0, calc(100% - 1em) 0,
@@ -143,7 +118,7 @@ watchEffect(() => {
0 0 0 0
); );
} }
.breadcrumb > a:only-child { .breadcrumb a:only-child {
clip-path: polygon( clip-path: polygon(
0 0, 0 0,
calc(100% - 1em) 0, calc(100% - 1em) 0,
@@ -155,9 +130,9 @@ watchEffect(() => {
} }
.breadcrumb svg { .breadcrumb svg {
/* FIXME: Custom positioning to align it well; needs proper solution */ /* FIXME: Custom positioning to align it well; needs proper solution */
padding-left: 0.8em;
width: 1.3em; width: 1.3em;
height: 1.3em; height: 1.3em;
margin: -.5em;
fill: var(--breadcrumb-color); fill: var(--breadcrumb-color);
transition: fill var(--breadcrumb-transtime); transition: fill var(--breadcrumb-transtime);
} }
@@ -177,6 +152,6 @@ watchEffect(() => {
} }
.breadcrumb a:hover { color: var(--breadcrumb-hover-color) } .breadcrumb a:hover { color: var(--breadcrumb-hover-color) }
.breadcrumb a:hover svg { fill: var(--breadcrumb-hover-color) } .breadcrumb a:hover svg { fill: var(--breadcrumb-hover-color) }
.breadcrumb a.current { color: var(--accent-color); max-width: none; flex: 0 1 auto; } .breadcrumb a.current { color: var(--accent-color) }
.breadcrumb a.current svg { fill: var(--accent-color) } .breadcrumb a.current svg { fill: var(--accent-color) }
</style> </style>

View File

@@ -5,9 +5,9 @@
<th class="selection"> <th class="selection">
<input type="checkbox" tabindex="-1" v-model="allSelected" :indeterminate="selectionIndeterminate"> <input type="checkbox" tabindex="-1" v-model="allSelected" :indeterminate="selectionIndeterminate">
</th> </th>
<th class="sortcolumn" :class="{ sortactive: store.sortOrder === 'name' }" @click="store.toggleSort('name')">Name</th> <th class="sortcolumn" :class="{ sortactive: sort === 'name' }" @click="toggleSort('name')">Name</th>
<th class="sortcolumn modified right" :class="{ sortactive: store.sortOrder === 'modified' }" @click="store.toggleSort('modified')">Modified</th> <th class="sortcolumn modified right" :class="{ sortactive: sort === 'modified' }" @click="toggleSort('modified')">Modified</th>
<th class="sortcolumn size right" :class="{ sortactive: store.sortOrder === 'size' }" @click="store.toggleSort('size')">Size</th> <th class="sortcolumn size right" :class="{ sortactive: sort === 'size' }" @click="toggleSort('size')">Size</th>
<th class="menu"></th> <th class="menu"></th>
</tr> </tr>
</thead> </thead>
@@ -17,30 +17,30 @@
<td class="name"> <td class="name">
<FileRenameInput :doc="editing" :rename="mkdir" :exit="() => {editing = null}" /> <FileRenameInput :doc="editing" :rename="mkdir" :exit="() => {editing = null}" />
</td> </td>
<FileModified :doc=editing :key=nowkey /> <FileModified :doc=editing />
<FileSize :doc=editing /> <FileSize :doc=editing />
<td class="menu"></td> <td class="menu"></td>
</tr> </tr>
<template v-for="(doc, index) in documents" :key="doc.key"> <template v-for="(doc, index) in sortedDocuments" :key="doc.key">
<tr class="folder-change" v-if="showFolderBreadcrumb(index)"> <tr class="folder-change" v-if="showFolderBreadcrumb(index)">
<th colspan="5"><BreadCrumb :path="doc.loc ? doc.loc.split('/') : []" /></th> <th colspan="5"><BreadCrumb :path="doc.loc ? doc.loc.split('/') : []" /></th>
</tr> </tr>
<tr <tr
:id="`file-${doc.key}`" :id="`file-${doc.key}`"
:class="{ file: !doc.dir, folder: doc.dir, cursor: store.cursor === doc.key }" :class="{ file: !doc.dir, folder: doc.dir, cursor: cursor === doc }"
@click="store.cursor = store.cursor === doc.key ? '' : doc.key" @click="cursor = cursor === doc ? null : doc"
@contextmenu.prevent="contextMenu($event, doc)" @contextmenu.prevent="contextMenu($event, doc)"
> >
<td class="selection" @click.up.stop="store.cursor = store.cursor === doc.key ? doc.key : ''"> <td class="selection" @click.up.stop="cursor = cursor === doc ? doc : null">
<input <input
type="checkbox" type="checkbox"
tabindex="-1" tabindex="-1"
:checked="store.selected.has(doc.key)" :checked="documentStore.selected.has(doc.key)"
@change=" @change="
($event.target as HTMLInputElement).checked ($event.target as HTMLInputElement).checked
? store.selected.add(doc.key) ? documentStore.selected.add(doc.key)
: store.selected.delete(doc.key) : documentStore.selected.delete(doc.key)
" "
/> />
</td> </td>
@@ -49,16 +49,22 @@
<FileRenameInput :doc="doc" :rename="rename" :exit="() => {editing = null}" /> <FileRenameInput :doc="doc" :rename="rename" :exit="() => {editing = null}" />
</template> </template>
<template v-else> <template v-else>
<a :href=doc.url tabindex=-1 @contextmenu.stop @focus.stop="store.cursor = doc.key"> <a
{{ doc.name }} :href="url_for(doc)"
</a> tabindex="-1"
<button tabindex=-1 v-if="store.cursor == doc.key" class="rename-button" @click="() => (editing = doc)">🖊</button> @contextmenu.prevent
@focus.stop="cursor = doc"
@keyup.left="router.back()"
@keyup.right.stop="ev => { if (doc.dir) (ev.target as HTMLElement).click() }"
>{{ doc.name }}</a
>
<button v-if="cursor == doc" class="rename-button" @click="() => (editing = doc)">🖊</button>
</template> </template>
</td> </td>
<FileModified :doc=doc :key=nowkey /> <FileModified :doc=doc />
<FileSize :doc=doc /> <FileSize :doc=doc />
<td class="menu"> <td class="menu">
<button tabindex=-1 @click.stop="contextMenu($event, doc)"></button> <button tabindex="-1" @click.stop="contextMenu($event, doc)"></button>
</td> </td>
</tr> </tr>
</template> </template>
@@ -69,29 +75,32 @@
</tr> </tr>
</tbody> </tbody>
</table> </table>
<div v-else class="empty-container">Nothing to see here</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watchEffect, shallowRef, onMounted, onUnmounted } from 'vue' import { ref, computed, watchEffect } from 'vue'
import { useMainStore } from '@/stores/main' import { useDocumentStore } from '@/stores/documents'
import { Doc } from '@/repositories/Document' import type { Document } from '@/repositories/Document'
import FileRenameInput from './FileRenameInput.vue' import FileRenameInput from './FileRenameInput.vue'
import { connect, controlUrl } from '@/repositories/WS' import { connect, controlUrl } from '@/repositories/WS'
import { formatSize } from '@/utils' import { collator, formatSize, formatUnixDate } from '@/utils'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import ContextMenu from '@imengyu/vue3-context-menu'
import type { SortOrder } from '@/utils/docsort'
import type SvgButtonVue from './SvgButton.vue'
const props = defineProps<{ const props = defineProps<{
path: Array<string> path: Array<string>
documents: Doc[] documents: Document[]
}>() }>()
const store = useMainStore() const documentStore = useDocumentStore()
const router = useRouter() const router = useRouter()
const url_for = (doc: Document) => {
const p = doc.loc ? `${doc.loc}/${doc.name}` : doc.name
return doc.dir ? `#/${p}/` : `/files/${p}`
}
const cursor = ref<Document | null>(null)
// File rename // File rename
const editing = shallowRef<Doc | null>(null) const editing = ref<Document | null>(null)
const rename = (doc: Doc, newName: string) => { const rename = (doc: Document, newName: string) => {
const oldName = doc.name const oldName = doc.name
const control = connect(controlUrl, { const control = connect(controlUrl, {
message(ev: MessageEvent) { message(ev: MessageEvent) {
@@ -115,69 +124,75 @@ const rename = (doc: Doc, newName: string) => {
} }
doc.name = newName // We should get an update from watch but this is quicker doc.name = newName // We should get an update from watch but this is quicker
} }
const sortedDocuments = computed(() => sorted(props.documents as Document[]))
const showFolderBreadcrumb = (i: number) => {
const docs = sortedDocuments.value
const docloc = docs[i].loc
return i === 0 ? docloc !== loc.value : docloc !== docs[i - 1].loc
}
defineExpose({ defineExpose({
newFolder() { newFolder() {
const now = Math.floor(Date.now() / 1000) const now = Date.now() / 1000
editing.value = new Doc({ editing.value = {
loc: loc.value, loc: loc.value,
key: 'new', key: 'new',
name: 'New Folder', name: 'New Folder',
dir: true, dir: true,
mtime: now, mtime: now,
size: 0, size: 0,
}) sizedisp: formatSize(0),
modified: formatUnixDate(now),
haystack: '',
}
console.log("New")
}, },
toggleSelectAll() { toggleSelectAll() {
console.log('Select') console.log('Select')
allSelected.value = !allSelected.value allSelected.value = !allSelected.value
}, },
toggleSortColumn(column: number) {
const columns = ['', 'name', 'modified', 'size', '']
toggleSort(columns[column])
},
isCursor() { isCursor() {
return store.cursor && editing.value === null return cursor.value !== null && editing.value === null
}, },
cursorRename() { cursorRename() {
editing.value = props.documents.find(doc => doc.key === store.cursor) ?? null editing.value = cursor.value
}, },
cursorSelect() { cursorSelect() {
const key = store.cursor const doc = cursor.value
if (!key) return if (!doc) return
if (store.selected.has(key)) { if (documentStore.selected.has(doc.key)) {
store.selected.delete(key) documentStore.selected.delete(doc.key)
} else { } else {
store.selected.add(key) documentStore.selected.add(doc.key)
} }
this.cursorMove(1, null) this.cursorMove(1)
}, },
up(ev: KeyboardEvent) { this.cursorMove(-1, ev) }, cursorMove(d: number, select = false) {
down(ev: KeyboardEvent) { this.cursorMove(1, ev) },
left(ev: KeyboardEvent) { router.back() },
right(ev: KeyboardEvent) {
const a = document.querySelector(`#file-${store.cursor} a`) as HTMLAnchorElement | null
if (a) a.click()
},
cursorMove(d: number, ev: KeyboardEvent | null) {
const select = !!ev?.shiftKey
// Move cursor up or down (keyboard navigation) // Move cursor up or down (keyboard navigation)
const docs = props.documents const documents = sortedDocuments.value
if (docs.length === 0) { if (documents.length === 0) {
store.cursor = '' cursor.value = null
return return
} }
const N = docs.length const N = documents.length
const mod = (a: number, b: number) => ((a % b) + b) % b const mod = (a: number, b: number) => ((a % b) + b) % b
const increment = (i: number, d: number) => mod(i + d, N + 1) const increment = (i: number, d: number) => mod(i + d, N + 1)
const index = const index =
store.cursor ? docs.findIndex(doc => doc.key === store.cursor) : docs.length cursor.value !== null ? documents.indexOf(cursor.value) : documents.length
const moveto = increment(index, d) const moveto = increment(index, d)
store.cursor = docs[moveto]?.key ?? '' cursor.value = documents[moveto] ?? null
const tr = store.cursor ? document.getElementById(`file-${store.cursor}`) : '' const tr = cursor.value ? document.getElementById(`file-${cursor.value.key}`) : null
if (select) { if (select) {
// Go forwards, possibly wrapping over the end; the last entry is not toggled // Go forwards, possibly wrapping over the end; the last entry is not toggled
let [begin, end] = d > 0 ? [index, moveto] : [moveto, index] let [begin, end] = d > 0 ? [index, moveto] : [moveto, index]
for (let p = begin; p !== end; p = increment(p, 1)) { for (let p = begin; p !== end; p = increment(p, 1)) {
if (p === N) continue if (p === N) continue
const key = docs[p].key const key = documents[p].key
if (store.selected.has(key)) store.selected.delete(key) if (documentStore.selected.has(key)) documentStore.selected.delete(key)
else store.selected.add(key) else documentStore.selected.add(key)
} }
} }
// @ts-ignore // @ts-ignore
@@ -199,29 +214,22 @@ const focusBreadcrumb = () => {
let scrolltimer: any = null let scrolltimer: any = null
let scrolltr: any = null let scrolltr: any = null
watchEffect(() => { watchEffect(() => {
if (store.cursor && store.cursor !== editing.value?.key) editing.value = null if (cursor.value && cursor.value !== editing.value) editing.value = null
if (editing.value) store.cursor = editing.value?.key if (editing.value) cursor.value = editing.value
if (store.cursor) { if (cursor.value) {
const a = document.querySelector( const a = document.querySelector(
`#file-${store.cursor} .name a` `#file-${cursor.value.key} .name a`
) as HTMLAnchorElement | null ) as HTMLAnchorElement | null
if (a) a.focus() if (a) a.focus()
} }
}) })
watchEffect(() => { watchEffect(() => {
if (!props.documents.length && store.cursor) { if (!props.documents.length && cursor.value) {
store.cursor = '' cursor.value = null
focusBreadcrumb() focusBreadcrumb()
} }
}) })
let nowkey = ref(0) const mkdir = (doc: Document, name: string) => {
let modifiedTimer: any = null
const updateModified = () => {
nowkey.value = Math.floor(Date.now() / 1000)
}
onMounted(() => { updateModified(); modifiedTimer = setInterval(updateModified, 1000) })
onUnmounted(() => { clearInterval(modifiedTimer) })
const mkdir = (doc: Doc, name: string) => {
const control = connect(controlUrl, { const control = connect(controlUrl, {
open() { open() {
control.send( control.send(
@@ -238,24 +246,34 @@ const mkdir = (doc: Doc, name: string) => {
editing.value = null editing.value = null
} else { } else {
console.log('mkdir', msg) console.log('mkdir', msg)
router.push(doc.urlrouter) router.push(doc.loc ? `/${doc.loc}/${name}/` : `/${name}/`)
} }
} }
}) })
// We should get an update from watch but this is quicker doc.name = name // We should get an update from watch but this is quicker
doc.name = name
doc.key = crypto.randomUUID()
} }
const showFolderBreadcrumb = (i: number) => {
const docs = props.documents // Column sort
const docloc = docs[i].loc const toggleSort = (name: string) => {
return i === 0 ? docloc !== loc.value : docloc !== docs[i - 1].loc sort.value = sort.value === name ? '' : name
}
const sort = ref<string>('')
const sortCompare = {
name: (a: Document, b: Document) => collator.compare(a.name, b.name),
modified: (a: Document, b: Document) => b.mtime - a.mtime,
size: (a: Document, b: Document) => b.size - a.size
}
const sorted = (documents: Document[]) => {
const cmp = sortCompare[sort.value as keyof typeof sortCompare]
const sorted = [...documents]
if (cmp) sorted.sort(cmp)
return sorted
} }
const selectionIndeterminate = computed({ const selectionIndeterminate = computed({
get: () => { get: () => {
return ( return (
props.documents.length > 0 && props.documents.length > 0 &&
props.documents.some((doc: Doc) => store.selected.has(doc.key)) && props.documents.some((doc: Document) => documentStore.selected.has(doc.key)) &&
!allSelected.value !allSelected.value
) )
}, },
@@ -266,16 +284,16 @@ const allSelected = computed({
get: () => { get: () => {
return ( return (
props.documents.length > 0 && props.documents.length > 0 &&
props.documents.every((doc: Doc) => store.selected.has(doc.key)) props.documents.every((doc: Document) => documentStore.selected.has(doc.key))
) )
}, },
set: (value: boolean) => { set: (value: boolean) => {
console.log('Setting allSelected', value) console.log('Setting allSelected', value)
for (const doc of props.documents) { for (const doc of props.documents) {
if (value) { if (value) {
store.selected.add(doc.key) documentStore.selected.add(doc.key)
} else { } else {
store.selected.delete(doc.key) documentStore.selected.delete(doc.key)
} }
} }
} }
@@ -283,13 +301,9 @@ const allSelected = computed({
const loc = computed(() => props.path.join('/')) const loc = computed(() => props.path.join('/'))
const contextMenu = (ev: MouseEvent, doc: Doc) => { const contextMenu = (ev: Event, doc: Document) => {
store.cursor = doc.key cursor.value = doc
ContextMenu.showContextMenu({ console.log('Context menu', ev, doc)
x: ev.x, y: ev.y, items: [
{ label: 'Rename', onClick: () => { editing.value = doc } },
],
})
} }
</script> </script>
@@ -307,36 +321,29 @@ tbody tr {
position: relative; position: relative;
z-index: auto; z-index: auto;
} }
table thead .selection input[type='checkbox'] { table thead input[type='checkbox'] {
position: inherit; position: inherit;
width: 1rem; width: 1em;
height: 1rem; height: 1em;
padding: 0; padding: 0.5rem 0.5em;
margin: auto;
} }
table tbody .selection input[type='checkbox'] { table tbody input[type='checkbox'] {
width: 2rem; width: 2rem;
height: 2rem; height: 2rem;
} }
table .selection { table .selection {
width: 3rem; width: 2rem;
text-align: center; text-align: center;
text-overflow: clip; text-overflow: clip;
padding: 0;
}
table .selection input {
margin: auto;
} }
table .modified { table .modified {
width: 10rem; width: 9em;
text-overflow: clip;
} }
table .size { table .size {
width: 7rem; width: 5em;
text-overflow: clip;
} }
table .menu { table .menu {
width: 2rem; width: 1rem;
} }
tbody td { tbody td {
font-size: 1.2rem; font-size: 1.2rem;
@@ -371,7 +378,7 @@ table td {
} }
} }
thead tr { thead tr {
font-size: 0.8rem; font-size: var(--header-font-size);
background: linear-gradient(to bottom, #eee, #fff 30%, #ddd); background: linear-gradient(to bottom, #eee, #fff 30%, #ddd);
color: #000; color: #000;
box-shadow: 0 0 .2rem black; box-shadow: 0 0 .2rem black;
@@ -392,11 +399,9 @@ tbody tr.cursor {
padding-right: 1.5rem; padding-right: 1.5rem;
} }
.sortcolumn::after { .sortcolumn::after {
font-size: 1rem;
content: '▸'; content: '▸';
color: #888; color: #888;
margin-left: 0.5rem; margin-left: 0.5em;
margin-top: -.2rem;
position: absolute; position: absolute;
transition: all var(--transition-time) linear; transition: all var(--transition-time) linear;
} }
@@ -446,4 +451,3 @@ tbody .selection input {
color: #888; color: #888;
} }
</style> </style>
@/stores/main

View File

@@ -5,7 +5,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { Doc } from '@/repositories/Document' import type { Document } from '@/repositories/Document'
import { computed } from 'vue' import { computed } from 'vue'
const datetime = computed(() => const datetime = computed(() =>
@@ -17,6 +17,6 @@ const tooltip = computed(() =>
) )
const props = defineProps<{ const props = defineProps<{
doc: Doc doc: Document
}>() }>()
</script> </script>

View File

@@ -12,7 +12,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { Doc } from '@/repositories/Document' import type { Document } from '@/repositories/Document'
import { ref, onMounted, nextTick } from 'vue' import { ref, onMounted, nextTick } from 'vue'
const input = ref<HTMLInputElement | null>(null) const input = ref<HTMLInputElement | null>(null)
@@ -28,8 +28,8 @@ onMounted(() => {
}) })
const props = defineProps<{ const props = defineProps<{
doc: Doc doc: Document
rename: (doc: Doc, newName: string) => void rename: (doc: Document, newName: string) => void
exit: () => void exit: () => void
}>() }>()

View File

@@ -3,7 +3,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { Doc } from '@/repositories/Document' import type { Document } from '@/repositories/Document'
import { computed } from 'vue' import { computed } from 'vue'
const sizeClass = computed(() => { const sizeClass = computed(() => {
@@ -12,7 +12,7 @@ const sizeClass = computed(() => {
}) })
const props = defineProps<{ const props = defineProps<{
doc: Doc doc: Document
}>() }>()
</script> </script>

View File

@@ -0,0 +1,52 @@
<template>
<object
v-if="props.type === 'pdf'"
:data="dataURL"
type="application/pdf"
width="100%"
height="100%"
></object>
<a-image
v-else-if="props.type === 'image'"
width="50%"
:src="dataURL"
@click="() => setVisible(true)"
:previewMask="false"
:preview="{
visibleImg,
onVisibleChange: setVisible
}"
/>
<!-- Unknown case -->
<h1 v-else>Unsupported file type</h1>
</template>
<script setup lang="ts">
import { watchEffect, ref } from 'vue'
import Router from '@/router/index'
import { url_document_get } from '@/repositories/Document'
const dataURL = ref('')
watchEffect(() => {
dataURL.value = new URL(
url_document_get + Router.currentRoute.value.path,
location.origin
).toString()
})
const emit = defineEmits({
visibleImg(value: boolean) {
return value
}
})
function setVisible(value: boolean) {
emit('visibleImg', value)
}
const props = defineProps<{
type?: string
visibleImg: boolean
}>()
</script>
<style></style>

View File

@@ -1,254 +0,0 @@
<template>
<div v-if="props.documents.length || editing" class="gallery" ref="gallery">
<GalleryFigure v-for="(doc, index) in documents" :key="doc.key" :doc="doc" :index="index">
<BreadCrumb :path="doc.loc ? doc.loc.split('/') : []" v-if="showFolderBreadcrumb(index)" class="folder-change"/>
</GalleryFigure>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watchEffect, shallowRef, onMounted, onUnmounted, nextTick } from 'vue'
import { useMainStore } from '@/stores/main'
import { Doc } from '@/repositories/Document'
import FileRenameInput from './FileRenameInput.vue'
import { connect, controlUrl } from '@/repositories/WS'
import { formatSize } from '@/utils'
import { useRouter } from 'vue-router'
import ContextMenu from '@imengyu/vue3-context-menu'
import type { SortOrder } from '@/utils/docsort'
const props = defineProps<{
path: Array<string>
documents: Doc[]
}>()
const store = useMainStore()
const router = useRouter()
// File rename
const editing = shallowRef<Doc | null>(null)
const rename = (doc: Doc, newName: string) => {
const oldName = doc.name
const control = connect(controlUrl, {
message(ev: MessageEvent) {
const msg = JSON.parse(ev.data)
if ('error' in msg) {
console.error('Rename failed', msg.error.message, msg.error)
doc.name = oldName
} else {
console.log('Rename succeeded', msg)
}
}
})
control.onopen = () => {
control.send(
JSON.stringify({
op: 'rename',
path: `${doc.loc}/${oldName}`,
to: newName
})
)
}
doc.name = newName // We should get an update from watch but this is quicker
}
const gallery = ref<HTMLElement>()
const columns = computed(() => {
if (!gallery.value) return 1
return getComputedStyle(gallery.value).gridTemplateColumns.split(' ').length
})
defineExpose({
newFolder() {
const now = Math.floor(Date.now() / 1000)
editing.value = new Doc({
loc: loc.value,
key: 'new',
name: 'New Folder',
dir: true,
mtime: now,
size: 0,
})
},
toggleSelectAll() {
console.log('Select')
allSelected.value = !allSelected.value
},
toggleSortColumn(column: number) {
const order = ['', 'name', 'modified', 'size', ''][column]
if (order) store.toggleSort(order as SortOrder)
},
isCursor() {
return store.cursor && editing.value === null
},
cursorRename() {
editing.value = props.documents.find(doc => doc.key === store.cursor) ?? null
},
cursorSelect() {
const key = store.cursor
if (!key) return
if (store.selected.has(key)) {
store.selected.delete(key)
} else {
store.selected.add(key)
}
this.cursorMove(1, null)
},
up(ev: KeyboardEvent) { this.cursorMove(-columns.value, ev) },
down(ev: KeyboardEvent) { this.cursorMove(columns.value, ev) },
left(ev: KeyboardEvent) { this.cursorMove(-1, ev) },
right(ev: KeyboardEvent) { this.cursorMove(1, ev) },
cursorMove(d: number, ev: KeyboardEvent | null) {
const select = !!ev?.shiftKey
// Move cursor up or down (keyboard navigation)
const docs = props.documents
if (docs.length === 0) {
store.cursor = ''
return
}
const N = docs.length
const mod = (a: number, b: number) => ((a % b) + b) % b
const increment = (i: number, d: number) => mod(i + d, N + 1)
const index =
store.cursor ? docs.findIndex(doc => doc.key === store.cursor) : N
let moveto
if (index === N) moveto = d > 0 ? 0 : N - 1
else {
moveto = increment(index, d)
// Wrapping either end, just land outside the list
if (Math.abs(d) >= N || Math.sign(d) !== Math.sign(moveto - index)) moveto = N
}
console.log("Gallery cursorMove", d, index, moveto, moveto - index)
store.cursor = docs[moveto]?.key ?? ''
const tr = store.cursor ? document.getElementById(`file-${store.cursor}`) : ''
if (select) {
// Go forwards, possibly wrapping over the end; the last entry is not toggled
let [begin, end] = d > 0 ? [index, moveto] : [moveto, index]
for (let p = begin; p !== end; p = increment(p, 1)) {
if (p === N) continue
const key = docs[p].key
if (store.selected.has(key)) store.selected.delete(key)
else store.selected.add(key)
}
}
// @ts-ignore
scrolltr = tr
if (!scrolltimer) {
scrolltimer = setTimeout(() => {
if (scrolltr)
scrolltr.scrollIntoView({ block: 'center', behavior: 'smooth' })
scrolltimer = null
}, 300)
}
if (moveto === N) focusBreadcrumb()
}
})
const focusBreadcrumb = () => {
const el = document.querySelector('.breadcrumb') as HTMLElement | null
if (el) el.focus()
}
let scrolltimer: any = null
let scrolltr: any = null
watchEffect(() => {
if (store.cursor && store.cursor !== editing.value?.key) editing.value = null
if (editing.value) store.cursor = editing.value.key
if (store.cursor) {
const a = document.querySelector(`#file-${store.cursor}`) as HTMLAnchorElement | null
if (a) { a.focus(); a.scrollIntoView({ block: 'center', behavior: 'smooth' }) }
}
})
watchEffect(() => {
if (!props.documents.length && store.cursor) {
store.cursor = ''
focusBreadcrumb()
}
})
let nowkey = ref(0)
let modifiedTimer: any = null
const updateModified = () => {
nowkey.value = Math.floor(Date.now() / 1000)
}
onMounted(() => { updateModified(); modifiedTimer = setInterval(updateModified, 1000) })
onUnmounted(() => { clearInterval(modifiedTimer) })
const mkdir = (doc: Doc, name: string) => {
const control = connect(controlUrl, {
open() {
control.send(
JSON.stringify({
op: 'mkdir',
path: `${doc.loc}/${name}`
})
)
},
message(ev: MessageEvent) {
const msg = JSON.parse(ev.data)
if ('error' in msg) {
console.error('Mkdir failed', msg.error.message, msg.error)
editing.value = null
} else {
console.log('mkdir', msg)
router.push(doc.urlrouter)
}
}
})
// We should get an update from watch but this is quicker
doc.name = name
doc.key = crypto.randomUUID()
}
const showFolderBreadcrumb = (i: number) => {
const docs = props.documents
const docloc = docs[i].loc
return i === 0 ? docloc !== loc.value : docloc !== docs[i - 1].loc
}
const selectionIndeterminate = computed({
get: () => {
return (
props.documents.length > 0 &&
props.documents.some((doc: Doc) => store.selected.has(doc.key)) &&
!allSelected.value
)
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
set: (value: boolean) => {}
})
const allSelected = computed({
get: () => {
return (
props.documents.length > 0 &&
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) {
store.selected.add(doc.key)
} else {
store.selected.delete(doc.key)
}
}
}
})
const loc = computed(() => props.path.join('/'))
const contextMenu = (ev: MouseEvent, doc: Doc) => {
store.cursor = doc.key
ContextMenu.showContextMenu({
x: ev.x, y: ev.y, items: [
{ label: 'Rename', onClick: () => { editing.value = doc } },
],
})
}
</script>
<style scoped>
.gallery {
padding: 1rem;
width: 100%;
display: grid;
gap: .5rem;
grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
grid-auto-rows: 15rem;
}
.breadcrumb {
position: absolute;
z-index: 1;
}
</style>

View File

@@ -1,94 +0,0 @@
<template>
<a :id="`file-${doc.key}`" :href=doc.url tabindex=-1
:class="{ file: !doc.dir, folder: doc.dir, cursor: store.cursor === doc.key }"
@contextmenu.stop
@focus.stop="store.cursor = doc.key"
@click="ev => {
if (m!.play()) ev.preventDefault()
store.cursor = doc.key
}"
>
<figure>
<slot></slot>
<MediaPreview ref=m :doc="doc" :tabindex=-1 />
<caption>
<label>
<SelectBox :doc=doc />
<span :title="doc.name + '\n' + doc.modified + '\n' + doc.sizedisp">{{ doc.name }}</span>
</label>
</caption>
</figure>
</a>
</template>
<script setup lang=ts>
import { ref } from 'vue'
import { useMainStore } from '@/stores/main'
import { Doc } from '@/repositories/Document'
import MediaPreview from '@/components/MediaPreview.vue'
const store = useMainStore()
const props = defineProps<{
doc: Doc
index: number
}>()
const m = ref<typeof MediaPreview | null>(null)
</script>
<style scoped>
.gallery figure {
height: 15rem;
position: relative;
border-radius: .5rem;
overflow: hidden;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
overflow: hidden;
}
figure caption {
font-weight: 600;
color: var(--text-color);
text-shadow: 0 0 .2rem #000, 0 0 1rem #000;
}
.cursor caption {
background: var(--accent-color);
}
caption {
position: absolute;
overflow: hidden;
bottom: 0;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
caption label {
width: 100%;
display: flex;
align-items: center;
}
label span {
flex: 1 1;
margin-right: 2rem;
text-align: center;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
label input[type='checkbox'] {
width: 2rem;
height: 2rem;
opacity: 0;
flex-shrink: 0;
}
label input[type='checkbox']:checked {
opacity: 1;
}
a {
text-decoration: none;
}
</style>

View File

@@ -1,67 +1,66 @@
<template> <template>
<nav class="headermain buttons"> <nav class="headermain">
<template v-if="store.error"> <div class="buttons">
<div class="error-message" @click="store.error = ''">{{ store.error }}</div> <template v-if="documentStore.error">
<div class="smallgap"></div> <div class="error-message" @click="documentStore.error = ''">{{ documentStore.error }}</div>
</template> <div class="smallgap"></div>
<UploadButton :path="props.path" /> </template>
<SvgButton <UploadButton :path="props.path" />
name="create-folder" <SvgButton
data-tooltip="New folder" name="create-folder"
@click="() => store.fileExplorer!.newFolder()" data-tooltip="New folder"
/> @click="() => documentStore.fileExplorer.newFolder()"
<slot></slot>
<div class="spacer smallgap"></div>
<template v-if="showSearchInput">
<input
ref="search"
type="search"
:value="query"
@input="updateSearch"
placeholder="Find files"
class="margin-input"
/> />
</template> <slot></slot>
<SvgButton ref="searchButton" name="find" @click.prevent="toggleSearchInput" /> <div class="spacer smallgap"></div>
<SvgButton name="eye" @click="store.prefs.gallery = !store.prefs.gallery" /> <template v-if="showSearchInput">
<SvgButton name="cog" @click="settingsMenu" /> <input
ref="search"
type="search"
:value="query"
@blur="ev => { if (!query) closeSearch(ev) }"
@input="updateSearch"
placeholder="Search words"
class="margin-input"
@keyup.escape="closeSearch"
/>
</template>
<SvgButton ref="searchButton" name="find" @click.prevent="toggleSearchInput" />
<SvgButton name="cog" @click="settingsMenu" />
</div>
</nav> </nav>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { useMainStore } from '@/stores/main' import { useDocumentStore } from '@/stores/documents'
import { ref, nextTick, watchEffect } from 'vue' import { ref, nextTick, watchEffect } from 'vue'
import ContextMenu from '@imengyu/vue3-context-menu' import ContextMenu from '@imengyu/vue3-context-menu'
import router from '@/router'; import router from '@/router';
const store = useMainStore() const documentStore = useDocumentStore()
const showSearchInput = ref<boolean>(false) const showSearchInput = ref<boolean>(false)
const search = ref<HTMLInputElement | null>() const search = ref<HTMLInputElement | null>()
const searchButton = ref<HTMLButtonElement | null>() const searchButton = ref<HTMLButtonElement | null>()
const props = defineProps<{
path: Array<string>
query: string
}>()
const closeSearch = (ev: Event) => { const closeSearch = ev => {
if (!showSearchInput.value) return // Already closing if (!showSearchInput.value) return // Already closing
showSearchInput.value = false showSearchInput.value = false
const breadcrumb = document.querySelector('.breadcrumb') as HTMLElement const breadcrumb = document.querySelector('.breadcrumb') as HTMLElement
breadcrumb.focus() breadcrumb.focus()
updateSearch(ev) updateSearch(ev)
} }
const updateSearch = (ev: Event) => { const updateSearch = ev => {
const q = (ev.target as HTMLInputElement).value const q = ev.target.value
let p = props.path.join('/') let p = props.path.join('/')
p = p ? `/${p}` : '' p = p ? `/${p}` : ''
const url = q ? `${p}//${q}` : (p || '/') const url = q ? `${p}//${q}` : (p || '/')
const u = url.replaceAll('?', '%3F').replaceAll('#', '%23') console.log("Update search", url)
if (!props.query && q) router.push(u) if (!props.query && q) router.push(url)
else router.replace(u) else router.replace(url)
} }
const toggleSearchInput = (ev: Event) => { const toggleSearchInput = () => {
showSearchInput.value = !showSearchInput.value showSearchInput.value = !showSearchInput.value
if (!showSearchInput.value) return closeSearch(ev) if (!showSearchInput.value) return closeSearch()
nextTick(() => { nextTick(() => {
const input = search.value const input = search.value
if (input) input.focus() if (input) input.focus()
@@ -73,10 +72,10 @@ watchEffect(() => {
const settingsMenu = (e: Event) => { const settingsMenu = (e: Event) => {
// show the context menu // show the context menu
const items = [] const items = []
if (store.user.isLoggedIn) { if (documentStore.user.isLoggedIn) {
items.push({ label: `Logout ${store.user.username ?? ''}`, onClick: () => store.logout() }) items.push({ label: `Logout ${documentStore.user.username ?? ''}`, onClick: () => documentStore.logout() })
} else { } else {
items.push({ label: 'Login', onClick: () => store.loginDialog() }) items.push({ label: 'Login', onClick: () => documentStore.loginDialog() })
} }
ContextMenu.showContextMenu({ ContextMenu.showContextMenu({
// @ts-ignore // @ts-ignore
@@ -84,6 +83,11 @@ const settingsMenu = (e: Event) => {
items, items,
}) })
} }
const props = defineProps<{
path: Array<string>
query: string
}>()
defineExpose({ defineExpose({
toggleSearchInput, toggleSearchInput,
closeSearch, closeSearch,
@@ -92,18 +96,23 @@ defineExpose({
<style scoped> <style scoped>
.buttons { .buttons {
flex: 1000 0 auto;
padding: 0; padding: 0;
display: flex; display: flex;
align-items: center; align-items: center;
height: 3.5em;
z-index: 10; z-index: 10;
} }
.buttons > * {
flex-shrink: 1;
}
input[type='search'] { input[type='search'] {
background: var(--input-background); background: var(--input-background);
color: var(--input-color); color: var(--input-color);
border: 0; border: 0;
border-radius: 0.1em; border-radius: 0.1em;
padding: 0.5em;
outline: none; outline: none;
max-width: 15ch; font-size: 1.5em;
max-width: 30vw;
} }
</style> </style>

View File

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

View File

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

View File

@@ -1,100 +0,0 @@
<template>
<img v-if=doc.img :src="preview() ? doc.previewurl : doc.url" alt="">
<span v-else-if=doc.dir class="folder icon"></span>
<video ref=vid v-else-if=video() :src=doc.url controls preload=none @click.prevent>📄</video>
<audio ref=aud v-else-if=audio() :src=doc.url controls preload=metadata @click.stop>📄</audio>
<span v-else-if=archive() class="archive icon"></span>
<span v-else class="file icon" :class="`ext-${doc.ext}`"></span>
</template>
<script setup lang=ts>
import { compile, computed, ref } from 'vue'
import type { Doc } from '@/repositories/Document'
const aud = ref<HTMLAudioElement | null>(null)
const vid = ref<HTMLVideoElement | null>(null)
const media = computed(() => aud.value || vid.value)
const props = defineProps<{
doc: Doc
}>()
defineExpose({
play() {
if (media.value) {
if (media.value.paused) media.value.play()
else media.value.pause()
return true
}
return false
},
})
const video = () => ['mkv', 'mp4', 'webm', 'mov', 'avi'].includes(props.doc.ext)
const audio = () => ['mp3', 'flac', 'ogg', 'aac'].includes(props.doc.ext)
const archive = () => ['zip', 'tar', 'gz', 'bz2', 'xz', '7z', 'rar'].includes(props.doc.ext)
const preview = () => (
props.doc.size > 500000 &&
['png', 'bmp', 'ico', 'webp', 'avif', 'jpg', 'jpeg'].includes(props.doc.ext)
)
</script>
<style scoped>
img, embed, .icon {
font-size: 10em;
border-radius: .5rem;
overflow: hidden;
text-align: center;
object-fit: cover;
object-position: center;
min-width: 50%;
height: 100%;
}
audio, video {
height: 100%;
min-width: 50%;
max-width: 100%;
padding-bottom: 2rem;
margin: auto;
}
.folder::before {
content: '📁';
}
.folder:hover::before, .cursor .folder::before {
content: '📂';
}
.archive::before {
content: '📦';
}
.file::before {
content: '📄';
}
.ext-img::before {
content: '💿';
}
.ext-exe::before, .ext-msi::before, .ext-dmg::before, .ext-pkg::before {
content: '⚙️';
}
.ext-torrent::before {
content: '🏴‍☠️';
}
.icon {
filter: brightness(0.9);
}
figure.cursor .icon {
filter: brightness(1);
}
img::before, video::before {
/* broken image */
background: #888;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
text-align: center;
text-shadow: 0 0 .5rem #000;
filter: grayscale(1);
content: '❌';
}
</style>

View File

@@ -0,0 +1,27 @@
<template>
<template v-for="upload in documentStore.uploadingDocuments" :key="upload.key">
<span>{{ upload.name }}</span>
<div class="progress-container">
<a-progress :percent="upload.progress" />
<CloseCircleOutlined class="close-button" @click="dismissUpload(upload.key)" />
</div>
</template>
</template>
<script setup lang="ts">
import { useDocumentStore } from '@/stores/documents'
const documentStore = useDocumentStore()
function dismissUpload(key: number) {
documentStore.deleteUploadingDocument(key)
}
</script>
<style scoped>
.progress-container {
display: flex;
align-items: center;
}
.close-button:hover {
color: #b81414;
}
</style>

View File

@@ -1,22 +0,0 @@
<template>
<input type=checkbox tabindex=-1 :checked="store.selected.has(doc.key)"
@change="ev => {
if ((ev.target as HTMLInputElement).checked) {
store.selected.add(doc.key)
} else {
store.selected.delete(doc.key)
}
}"
>
</template>
<script setup lang=ts>
import { useMainStore } from '@/stores/main'
import type { Doc } from '@/repositories/Document'
const props = defineProps<{
doc: Doc
}>()
const store = useMainStore()
</script>

View File

@@ -6,7 +6,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { defineAsyncComponent } from 'vue' import { defineAsyncComponent, defineProps } from 'vue'
const props = defineProps<{ const props = defineProps<{
name: string name: string

View File

@@ -1,89 +1,39 @@
<script setup lang="ts"> <script setup lang="ts">
import { connect, uploadUrl } from '@/repositories/WS'; import { connect, uploadUrl } from '@/repositories/WS';
import { useMainStore } from '@/stores/main' import { useDocumentStore } from '@/stores/documents'
import { collator } from '@/utils'; import { collator } from '@/utils';
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue' import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
const fileInput = ref() const fileInput = ref()
const folderInput = ref() const folderInput = ref()
const store = useMainStore() const documentStore = useDocumentStore()
const props = defineProps({ const props = defineProps({
path: Array<string> path: Array<string>
}) })
type CloudFile = {
file: File
cloudName: string
cloudPos: number
}
function pasteHandler(event: ClipboardEvent) {
const items = Array.from(event.clipboardData?.items ?? [])
const infiles = [] as File[]
const dirs = [] as FileSystemDirectoryEntry[]
for (const item of items) {
if (item.kind !== 'file') continue
const entry = item.webkitGetAsEntry()
if (entry?.isFile) {
const file = item.getAsFile()
if (file) infiles.push(file)
} else if (entry?.isDirectory) {
dirs.push(entry as FileSystemDirectoryEntry)
}
}
if (infiles.length || dirs.length) {
event.preventDefault()
uploadFiles(infiles)
for (const entry of dirs) pasteDirectory(entry, `${props.path!.join('/')}/${entry.name}`)
}
}
const pasteDirectory = async (entry: FileSystemDirectoryEntry, loc: string) => {
const reader = entry.createReader()
const entries = await new Promise<any[]>(resolve => reader.readEntries(resolve))
const cloudfiles = [] as CloudFile[]
for (const entry of entries) {
const cloudName = `${loc}/${entry.name}`
if (entry.isFile) {
const file = await new Promise(resolve => entry.file(resolve)) as File
cloudfiles.push({file, cloudName, cloudPos: 0})
} else if (entry.isDirectory) {
await pasteDirectory(entry, cloudName)
}
}
if (cloudfiles.length) uploadCloudFiles(cloudfiles)
}
function uploadHandler(event: Event) { function uploadHandler(event: Event) {
event.preventDefault() event.preventDefault()
event.stopPropagation()
// @ts-ignore // @ts-ignore
const input = event.target as HTMLInputElement | null let infiles = Array.from(event.dataTransfer?.files || event.target.files) as File[]
const infiles = Array.from((input ?? (event as DragEvent).dataTransfer)?.files ?? []) as File[] if (!infiles.length) return
if (input) input.value = ''
if (infiles.length) uploadFiles(infiles)
}
const uploadFiles = (infiles: File[]) => {
const loc = props.path!.join('/') const loc = props.path!.join('/')
let files = [] for (const f of infiles) {
for (const file of infiles) { f.cloudName = loc + '/' + (f.webkitRelativePath || f.name)
files.push({ f.cloudPos = 0
file,
cloudName: loc + '/' + (file.webkitRelativePath || file.name),
cloudPos: 0,
})
} }
uploadCloudFiles(files) const dotfiles = infiles.filter(f => f.cloudName.includes('/.'))
}
const uploadCloudFiles = (files: CloudFile[]) => {
const dotfiles = files.filter(f => f.cloudName.includes('/.'))
if (dotfiles.length) { if (dotfiles.length) {
store.error = "Won't upload dotfiles" documentStore.error = "Won't upload dotfiles"
console.log("Dotfiles omitted", dotfiles) console.log("Dotfiles omitted", dotfiles)
files = files.filter(f => !f.cloudName.includes('/.')) infiles = infiles.filter(f => !f.cloudName.includes('/.'))
} }
if (!files.length) return if (!infiles.length) return
files.sort((a, b) => collator.compare(a.cloudName, b.cloudName)) infiles.sort((a, b) => collator.compare(a.cloudName, b.cloudName))
// @ts-ignore // @ts-ignore
upqueue = [...upqueue, ...files] upqueue = upqueue.concat(infiles)
statsAdd(files) statsAdd(infiles)
startWorker() startWorker()
} }
@@ -99,14 +49,13 @@ const uprogress_init = {
tlast: 0, tlast: 0,
statbytes: 0, statbytes: 0,
statdur: 0, statdur: 0,
files: [] as CloudFile[], files: [],
filestart: 0, filestart: 0,
fileidx: 0, fileidx: 0,
filecount: 0, filecount: 0,
filename: '', filename: '',
filesize: 0, filesize: 0,
filepos: 0, filepos: 0,
status: 'idle',
} }
const uprogress = reactive({...uprogress_init}) const uprogress = reactive({...uprogress_init})
const percent = computed(() => uprogress.uploaded / uprogress.total * 100) const percent = computed(() => uprogress.uploaded / uprogress.total * 100)
@@ -117,7 +66,7 @@ const speed = computed(() => {
if (tsince > 1 / s) return 1 / tsince // Next block is late or not coming, decay if (tsince > 1 / s) return 1 / tsince // Next block is late or not coming, decay
return s // "Current speed" return s // "Current speed"
}) })
const speeddisp = computed(() => speed.value ? speed.value.toFixed(speed.value < 10 ? 1 : 0) + '\u202FMB/s': 'stalled') const speeddisp = computed(() => speed.value ? speed.value.toFixed(speed.value < 100 ? 1 : 0) + '\u202FMB/s': 'stalled')
setInterval(() => { setInterval(() => {
if (Date.now() - uprogress.tlast > 3000) { if (Date.now() - uprogress.tlast > 3000) {
// Reset // Reset
@@ -129,7 +78,7 @@ setInterval(() => {
uprogress.statdur *= .9 uprogress.statdur *= .9
} }
}, 100) }, 100)
const statUpdate = ({name, size, start, end}: {name: string, size: number, start: number, end: number}) => { const statUpdate = ({name, size, start, end}) => {
if (name !== uprogress.filename) return // If stats have been reset if (name !== uprogress.filename) return // If stats have been reset
const now = Date.now() const now = Date.now()
uprogress.uploaded = uprogress.filestart + end uprogress.uploaded = uprogress.filestart + end
@@ -148,7 +97,7 @@ const statNextFile = () => {
const f = uprogress.files.shift() const f = uprogress.files.shift()
if (!f) return statReset() if (!f) return statReset()
uprogress.filepos = 0 uprogress.filepos = 0
uprogress.filesize = f.file.size uprogress.filesize = f.size
uprogress.filename = f.cloudName uprogress.filename = f.cloudName
} }
const statReset = () => { const statReset = () => {
@@ -156,14 +105,14 @@ const statReset = () => {
uprogress.t0 = Date.now() uprogress.t0 = Date.now()
uprogress.tlast = uprogress.t0 + 1 uprogress.tlast = uprogress.t0 + 1
} }
const statsAdd = (f: CloudFile[]) => { const statsAdd = (f: Array<File>) => {
if (uprogress.files.length === 0) statReset() if (uprogress.files.length === 0) statReset()
uprogress.total += f.reduce((a, b) => a + b.file.size, 0) uprogress.total += f.reduce((a, b) => a + b.size, 0)
uprogress.filecount += f.length uprogress.filecount += f.length
uprogress.files = [...uprogress.files, ...f] uprogress.files = uprogress.files.concat(f)
statNextFile() statNextFile()
} }
let upqueue = [] as CloudFile[] let upqueue = [] as File[]
// TODO: Rewrite as WebSocket class // TODO: Rewrite as WebSocket class
const WSCreate = async () => await new Promise<WebSocket>(resolve => { const WSCreate = async () => await new Promise<WebSocket>(resolve => {
@@ -171,13 +120,13 @@ const WSCreate = async () => await new Promise<WebSocket>(resolve => {
open(ev: Event) { resolve(ws) }, open(ev: Event) { resolve(ws) },
error(ev: Event) { error(ev: Event) {
console.error('Upload socket error', ev) console.error('Upload socket error', ev)
store.error = 'Upload socket error' documentStore.error = 'Upload socket error'
}, },
message(ev: MessageEvent) { message(ev: MessageEvent) {
const res = JSON.parse(ev!.data) const res = JSON.parse(ev!.data)
if ('error' in res) { if ('error' in res) {
console.error('Upload socket error', res.error) console.error('Upload socket error', res.error)
store.error = res.error.message documentStore.error = res.error.message
return return
} }
if (res.status === 'ack') { if (res.status === 'ack') {
@@ -206,17 +155,18 @@ const worker = async () => {
const ws = await WSCreate() const ws = await WSCreate()
while (upqueue.length) { while (upqueue.length) {
const f = upqueue[0] const f = upqueue[0]
if (f.cloudPos === f.size) {
upqueue.shift()
continue
}
const start = f.cloudPos const start = f.cloudPos
const end = Math.min(f.file.size, start + (1<<20)) const end = Math.min(f.size, start + (1<<20))
const control = { name: f.cloudName, size: f.file.size, start, end } const control = { name: f.cloudName, size: f.size, start, end }
const data = f.file.slice(start, end) const data = f.slice(start, end)
f.cloudPos = end f.cloudPos = end
// Note: files may get modified during I/O // Note: files may get modified during I/O
// @ts-ignore FIXME proper WebSocket class, avoid attaching functions to WebSocket object
ws.sendMsg(control) ws.sendMsg(control)
// @ts-ignore
await ws.sendData(data) await ws.sendData(data)
if (f.cloudPos === f.file.size) upqueue.shift()
} }
if (upqueue.length) startWorker() if (upqueue.length) startWorker()
uprogress.status = "idle" uprogress.status = "idle"
@@ -234,10 +184,8 @@ onMounted(() => {
// Need to prevent both to prevent browser from opening the file // Need to prevent both to prevent browser from opening the file
addEventListener('dragover', uploadHandler) addEventListener('dragover', uploadHandler)
addEventListener('drop', uploadHandler) addEventListener('drop', uploadHandler)
addEventListener('paste', pasteHandler)
}) })
onUnmounted(() => { onUnmounted(() => {
removeEventListener('paste', pasteHandler)
removeEventListener('dragover', uploadHandler) removeEventListener('dragover', uploadHandler)
removeEventListener('drop', uploadHandler) removeEventListener('drop', uploadHandler)
}) })
@@ -259,7 +207,7 @@ onUnmounted(() => {
{{ (uprogress.filepos / uprogress.filesize * 100).toFixed(0) + '\u202F%' }} {{ (uprogress.filepos / uprogress.filesize * 100).toFixed(0) + '\u202F%' }}
</span> </span>
</span> </span>
<span class="position" v-if="uprogress.total > 1e7"> <span class="position" v-if="uprogress.filesize > 1e7">
{{ (uprogress.uploaded / 1e6).toFixed(0) + '\u202F/\u202F' + (uprogress.total / 1e6).toFixed(0) + '\u202FMB' }} {{ (uprogress.uploaded / 1e6).toFixed(0) + '\u202F/\u202F' + (uprogress.total / 1e6).toFixed(0) + '\u202FMB' }}
</span> </span>
<span class="speed">{{ speeddisp }}</span> <span class="speed">{{ speeddisp }}</span>
@@ -302,4 +250,3 @@ span {
.position { min-width: 4em } .position { min-width: 4em }
.speed { min-width: 4em } .speed { min-width: 4em }
</style> </style>
@/stores/main

View File

@@ -1,53 +1,17 @@
import { formatSize, formatUnixDate, haystackFormat } from "@/utils"
export type FUID = string export type FUID = string
export type DocProps = { export type Document = {
loc: string loc: string
name: string name: string
key: FUID key: FUID
size: number size: number
sizedisp: string
mtime: number mtime: number
modified: string
haystack: string
dir: boolean dir: boolean
} }
export class Doc {
private _name: string = ""
public loc: string = ""
public key: FUID = ""
public size: number = 0
public mtime: number = 0
public haystack: string = ""
public dir: boolean = false
constructor(props: Partial<DocProps> = {}) { Object.assign(this, props) }
get name() { return this._name }
set name(name: string) {
if (name.includes('/') || name.startsWith('.')) throw Error(`Invalid name: ${name}`)
this._name = name
this.haystack = haystackFormat(name)
}
get sizedisp(): string { return formatSize(this.size) }
get modified(): string { return formatUnixDate(this.mtime) }
get url(): string {
const p = this.loc ? `${this.loc}/${this.name}` : this.name
return this.dir ? '/#/' + `${p}/`.replaceAll('#', '%23') : `/files/${p}`.replaceAll('?', '%3F').replaceAll('#', '%23')
}
get urlrouter(): string {
return this.url.replace(/^\/#/, '')
}
get img(): boolean {
const ext = this.name.split('.').pop()?.toLowerCase()
return ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'svg'].includes(ext || '')
}
get previewurl(): string {
return this.url.replace(/^\/files/, '/preview')
}
get ext(): string {
const ext = this.name.split('.').pop()
return ext ? ext.toLowerCase() : ''
}
}
export type errorEvent = { export type errorEvent = {
error: { error: {
code: number code: number
@@ -72,7 +36,7 @@ export type UpdateEntry = ['k', number] | ['d', number] | ['i', Array<FileEntry>
// Helper structure for selections // Helper structure for selections
export interface SelectedItems { export interface SelectedItems {
keys: FUID[] keys: FUID[]
docs: Record<FUID, Doc> docs: Record<FUID, Document>
recursive: Array<[string, string, Doc]> recursive: Array<[string, string, Document]>
missing: Set<FUID> missing: Set<FUID>
} }

View File

@@ -1,4 +1,4 @@
import { useMainStore } from "@/stores/main" import { useDocumentStore } from "@/stores/documents"
import type { FileEntry, UpdateEntry, errorEvent } from "./Document" import type { FileEntry, UpdateEntry, errorEvent } from "./Document"
export const controlUrl = '/api/control' export const controlUrl = '/api/control'
@@ -6,26 +6,22 @@ export const uploadUrl = '/api/upload'
export const watchUrl = '/api/watch' export const watchUrl = '/api/watch'
let tree = [] as FileEntry[] let tree = [] as FileEntry[]
let reconnDelay = 500 let reconnectDuration = 500
let wsWatch = null as WebSocket | null let wsWatch = null as WebSocket | null
export const loadSession = () => { export const loadSession = () => {
const s = localStorage['cista-files'] const store = useDocumentStore()
if (!s) return false
const store = useMainStore()
try { try {
tree = JSON.parse(s) tree = JSON.parse(sessionStorage["cista-files"])
store.updateRoot(tree) store.updateRoot(tree)
console.log(`Loaded session with ${tree.length} items cached`)
return true return true
} catch (error) { } catch (error) {
console.log("Loading session failed", error)
return false return false
} }
} }
const saveSession = () => { const saveSession = () => {
localStorage["cista-files"] = JSON.stringify(tree) sessionStorage["cista-files"] = JSON.stringify(tree)
} }
export const connect = (path: string, handlers: Partial<Record<keyof WebSocketEventMap, any>>) => { export const connect = (path: string, handlers: Partial<Record<keyof WebSocketEventMap, any>>) => {
@@ -39,7 +35,7 @@ export const watchConnect = () => {
clearTimeout(watchTimeout) clearTimeout(watchTimeout)
watchTimeout = null watchTimeout = null
} }
const store = useMainStore() const store = useDocumentStore()
if (store.error !== 'Reconnecting...') store.error = 'Connecting...' if (store.error !== 'Reconnecting...') store.error = 'Connecting...'
console.log(store.error) console.log(store.error)
@@ -63,7 +59,7 @@ export const watchConnect = () => {
console.log('Connected to backend', msg) console.log('Connected to backend', msg)
store.server = msg.server store.server = msg.server
store.connected = true store.connected = true
reconnDelay = 500 reconnectDuration = 500
store.error = '' store.error = ''
if (msg.user) store.login(msg.user.username, msg.user.privileged) if (msg.user) store.login(msg.user.username, msg.user.privileged)
else if (store.isUserLogged) store.logout() else if (store.isUserLogged) store.logout()
@@ -81,16 +77,16 @@ export const watchDisconnect = () => {
let watchTimeout: any = null let watchTimeout: any = null
const watchReconnect = (event: MessageEvent) => { const watchReconnect = (event: MessageEvent) => {
const store = useMainStore() const store = useDocumentStore()
if (store.connected) { if (store.connected) {
console.warn("Disconnected from server", event) console.warn("Disconnected from server", event)
store.connected = false store.connected = false
store.error = 'Reconnecting...' store.error = 'Reconnecting...'
} }
reconnDelay = Math.min(5000, reconnDelay + 500) reconnectDuration = Math.min(5000, reconnectDuration + 500)
// The server closes the websocket after errors, so we need to reopen it // The server closes the websocket after errors, so we need to reopen it
if (watchTimeout !== null) clearTimeout(watchTimeout) if (watchTimeout !== null) clearTimeout(watchTimeout)
watchTimeout = setTimeout(watchConnect, reconnDelay) watchTimeout = setTimeout(watchConnect, reconnectDuration)
} }
@@ -113,8 +109,8 @@ const handleWatchMessage = (event: MessageEvent) => {
} }
} }
function handleRootMessage({ root }: { root: FileEntry[] }) { function handleRootMessage({ root }: { root: DirEntry }) {
const store = useMainStore() const store = useDocumentStore()
console.log('Watch root', root) console.log('Watch root', root)
store.updateRoot(root) store.updateRoot(root)
tree = root tree = root
@@ -122,7 +118,7 @@ function handleRootMessage({ root }: { root: FileEntry[] }) {
} }
function handleUpdateMessage(updateData: { update: UpdateEntry[] }) { function handleUpdateMessage(updateData: { update: UpdateEntry[] }) {
const store = useMainStore() const store = useDocumentStore()
const update = updateData.update const update = updateData.update
console.log('Watch update', update) console.log('Watch update', update)
if (!tree) return console.error('Watch update before root') if (!tree) return console.error('Watch update before root')
@@ -130,23 +126,23 @@ function handleUpdateMessage(updateData: { update: UpdateEntry[] }) {
let oidx = 0 let oidx = 0
for (const [action, arg] of update) { for (const [action, arg] of update) {
if (action === 'k') { if (action === 'k') {
newtree.push(...tree.slice(oidx, oidx + arg)) newtree.push(...tree.slice(oidx, oidx + arg))
oidx += arg oidx += arg
} }
else if (action === 'd') oidx += arg else if (action === 'd') oidx += arg
else if (action === 'i') newtree.push(...arg) else if (action === 'i') newtree.push(...arg)
else console.log("Unknown update action", action, arg) else console.log("Unknown update action", action, arg)
} }
if (oidx != tree.length) if (oidx != tree.length)
throw Error(`Tree update out of sync, number of entries mismatch: got ${oidx}, expected ${tree.length}, new tree ${newtree.length}`) throw Error(`Tree update out of sync, number of entries mismatch: got ${oidx}, expected ${tree.length}`)
store.updateRoot(newtree) store.updateRoot(newtree)
tree = newtree tree = newtree
saveSession() saveSession()
} }
function handleError(msg: errorEvent) { function handleError(msg: errorEvent) {
const store = useMainStore() const store = useDocumentStore()
if (msg.error.code === 401) { if (msg.error.code === 401) {
store.user.isOpenLoginModal = true store.user.isOpenLoginModal = true
store.user.isLoggedIn = false store.user.isLoggedIn = false

View File

@@ -1,12 +1,15 @@
import type { FileEntry, FUID, SelectedItems } from '@/repositories/Document' import type { Document, FileEntry, FUID, SelectedItems } from '@/repositories/Document'
import { Doc } from '@/repositories/Document' import { formatSize, formatUnixDate, haystackFormat } from '@/utils'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { collator } from '@/utils' import { collator } from '@/utils'
import { logoutUser } from '@/repositories/User' import { logoutUser } from '@/repositories/User'
import { watchConnect } from '@/repositories/WS' import { watchConnect } from '@/repositories/WS'
import { shallowRef } from 'vue' import { format } from 'path'
import { sorted, type SortOrder } from '@/utils/docsort'
type FileData = { id: string; mtime: number; size: number; dir: DirectoryData }
type DirectoryData = {
[filename: string]: FileData
}
type User = { type User = {
username: string username: string
privileged: boolean privileged: boolean
@@ -14,22 +17,17 @@ type User = {
isLoggedIn: boolean isLoggedIn: boolean
} }
export const useMainStore = defineStore({ export const useDocumentStore = defineStore({
id: 'main', id: 'documents',
state: () => ({ state: () => ({
document: shallowRef<Doc[]>([]), document: [] as Document[],
selected: new Set<FUID>(), selected: new Set<FUID>(),
query: '' as string, uploadingDocuments: [],
fileExplorer: null as any, uploadCount: 0 as number,
fileExplorer: null,
error: '' as string, error: '' as string,
connected: false, connected: false,
cursor: '' as string,
server: {} as Record<string, any>, server: {} as Record<string, any>,
prefs: {
gallery: false,
sortListing: '' as SortOrder,
sortFiltered: '' as SortOrder,
},
user: { user: {
username: '', username: '',
privileged: false, privileged: false,
@@ -37,26 +35,30 @@ export const useMainStore = defineStore({
isOpenLoginModal: false isOpenLoginModal: false
} as User } as User
}), }),
persist: {
paths: ['prefs'],
},
actions: { actions: {
updateRoot(root: FileEntry[]) { updateRoot(root: FileEntry[]) {
const docs = [] const docs = []
let loc = [] as string[] let loc = [] as string[]
for (const [level, name, key, mtime, size, isfile] of root) { for (const [level, name, key, mtime, size, isfile] of root) {
loc = loc.slice(0, level - 1) loc = loc.slice(0, level - 1)
docs.push(new Doc({ docs.push({
name, name,
loc: level ? loc.join('/') : '/', loc: level ? loc.join('/') : '/',
key, key,
size, size,
sizedisp: formatSize(size),
mtime, mtime,
modified: formatUnixDate(mtime),
haystack: haystackFormat(name),
dir: !isfile, dir: !isfile,
})) })
loc.push(name) loc.push(name)
} }
this.document = docs console.log("Documents", docs)
this.document = docs as Document[]
},
updateModified() {
for (const doc of this.document) doc.modified = formatUnixDate(doc.mtime)
}, },
login(username: string, privileged: boolean) { login(username: string, privileged: boolean) {
this.user.username = username this.user.username = username
@@ -72,25 +74,23 @@ export const useMainStore = defineStore({
console.log("Logout") console.log("Logout")
await logoutUser() await logoutUser()
this.$reset() this.$reset()
localStorage.clear()
history.go() // Reload page history.go() // Reload page
},
toggleSort(name: SortOrder) {
if (this.query) this.prefs.sortFiltered = this.prefs.sortFiltered === name ? '' : name
else this.prefs.sortListing = this.prefs.sortListing === name ? '' : name
},
sort(name: SortOrder | '') {
if (this.query) this.prefs.sortFiltered = name
else this.prefs.sortListing = name
},
focusBreadcrumb() {
(document.querySelector('.breadcrumb') as HTMLAnchorElement).focus()
} }
}, },
getters: { getters: {
sortOrder(): SortOrder { return this.query ? this.prefs.sortFiltered : this.prefs.sortListing }, isUserLogged(): boolean {
isUserLogged(): boolean { return this.user.isLoggedIn }, return this.user.isLoggedIn
recentDocuments(): Doc[] { return sorted(this.document, 'modified') }, },
recentDocuments(): Document[] {
const ret = [...this.document]
ret.sort((a, b) => b.mtime - a.mtime)
return ret
},
largeDocuments(): Document[] {
const ret = [...this.document]
ret.sort((a, b) => b.size - a.size)
return ret
},
selectedFiles(): SelectedItems { selectedFiles(): SelectedItems {
const selected = this.selected const selected = this.selected
const found = new Set<FUID>() const found = new Set<FUID>()
@@ -111,7 +111,7 @@ export const useMainStore = defineStore({
for (const key of selected) if (!found.has(key)) ret.missing.add(key) for (const key of selected) if (!found.has(key)) ret.missing.add(key)
// Build a flat list including contents recursively // Build a flat list including contents recursively
const relnames = new Set<string>() const relnames = new Set<string>()
function add(rel: string, full: string, doc: Doc) { function add(rel: string, full: string, doc: Document) {
if (!doc.dir && relnames.has(rel)) throw Error(`Multiple selections conflict for: ${rel}`) if (!doc.dir && relnames.has(rel)) throw Error(`Multiple selections conflict for: ${rel}`)
relnames.add(rel) relnames.add(rel)
ret.recursive.push([rel, full, doc]) ret.recursive.push([rel, full, doc])

View File

@@ -1,15 +0,0 @@
import { Doc } from '@/repositories/Document'
import { collator } from '@/utils'
export const ordering = {
name: (a: Doc, b: Doc) => collator.compare(a.name, b.name),
modified: (a: Doc, b: Doc) => b.mtime - a.mtime,
size: (a: Doc, b: Doc) => b.size - a.size
}
export type SortOrder = keyof typeof ordering | ''
export const sorted = (documents: Doc[], order: SortOrder) => {
if (!order) return documents
const sorted = [...documents]
sorted.sort(ordering[order])
return sorted
}

View File

@@ -86,7 +86,7 @@ export function haystackFormat(str: string) {
// Preformat search string for faster search // Preformat search string for faster search
export function needleFormat(query: string) { export function needleFormat(query: string) {
const based = query.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase() const based = query.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase()
return {based, words: based.split(/\s+/)} return {based, words: based.split(/\W+/)}
} }
// Test if haystack includes needle // Test if haystack includes needle

View File

@@ -1,42 +1,20 @@
<template> <template>
<div v-if="!props.path || documents.length === 0" class="empty-container">
<component :is="cog" class="cog"/>
<p v-if="!store.connected">No Connection</p>
<p v-else-if="store.document.length === 0">Waiting for File List</p>
<p v-else-if="store.query">No matches!</p>
<p v-else-if="!store.document.some(doc => (doc.loc ? `${doc.loc}/${doc.name}` : doc.name) === props.path.join('/'))">Folder not found.</p>
<p v-else>Empty folder</p>
</div>
<Gallery
v-else-if="store.prefs.gallery"
ref="fileExplorer"
:key="`gallery-${Router.currentRoute.value.path}`"
:path="props.path"
:documents="documents"
/>
<FileExplorer <FileExplorer
v-else
ref="fileExplorer" ref="fileExplorer"
:key="`explorer-${Router.currentRoute.value.path}`" :key="Router.currentRoute.value.path"
:path="props.path" :path="props.path"
:documents="documents" :documents="documents"
v-if="props.path"
/> />
<div v-if="!store.prefs.gallery && documents.some(doc => doc.img)" class="suggest-gallery">
<p>Media files found. Would you like a gallery view?</p>
<SvgButton name="eye" taborder=0 @click="() => { store.prefs.gallery = true }">Gallery</SvgButton>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { watchEffect, ref, computed } from 'vue' import { watchEffect, ref, computed } from 'vue'
import { useMainStore } from '@/stores/main' import { useDocumentStore } from '@/stores/documents'
import Router from '@/router/index' import Router from '@/router/index'
import { needleFormat, localeIncludes, collator } from '@/utils' import { needleFormat, localeIncludes, collator } from '@/utils';
import { sorted } from '@/utils/docsort'
import FileExplorer from '@/components/FileExplorer.vue'
import cog from '@/assets/svg/cog.svg'
const store = useMainStore() const documentStore = useDocumentStore()
const fileExplorer = ref() const fileExplorer = ref()
const props = defineProps<{ const props = defineProps<{
path: Array<string> path: Array<string>
@@ -46,25 +24,19 @@ const documents = computed(() => {
const loc = props.path.join('/') const loc = props.path.join('/')
const query = props.query const query = props.query
// List the current location // List the current location
if (!query) return sorted( if (!query) return documentStore.document.filter(doc => doc.loc === loc)
store.document.filter(doc => doc.loc === loc),
store.prefs.sortListing,
)
// Find up to 100 newest documents that match the search // Find up to 100 newest documents that match the search
const needle = needleFormat(query) const needle = needleFormat(query)
let limit = 100 let limit = 100
let docs = [] let docs = []
for (const doc of store.recentDocuments) { for (const doc of documentStore.recentDocuments) {
if (localeIncludes(doc.haystack, needle)) { if (localeIncludes(doc.haystack, needle)) {
docs.push(doc) docs.push(doc)
if (--limit === 0) break if (--limit === 0) break
} }
} }
// Organize by folder, by relevance
const locsub = loc + '/' const locsub = loc + '/'
// Custom sort override in effect?
const order = store.prefs.sortFiltered
if (order) return sorted(docs, order)
// Sort by relevance - current folder, then subfolders, then others
docs.sort((a, b) => ( docs.sort((a, b) => (
// @ts-ignore // @ts-ignore
(b.loc === loc) - (a.loc === loc) || (b.loc === loc) - (a.loc === loc) ||
@@ -81,43 +53,6 @@ const documents = computed(() => {
}) })
watchEffect(() => { watchEffect(() => {
store.fileExplorer = fileExplorer.value documentStore.fileExplorer = fileExplorer.value
store.query = props.query
}) })
</script> </script>
<style scoped>
.empty-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
font-size: 2rem;
text-shadow: 0 0 1rem #000, 0 0 2rem #000;
color: var(--accent-color);
}
@keyframes rotate {
0% { transform: rotate(0deg); }
100% { transform: rotate(359deg); }
}
.suggest-gallery p {
font-size: 2rem;
color: var(--accent-color);
}
.suggest-gallery {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
svg.cog {
width: 10rem;
height: 10rem;
margin: 0 auto;
animation: rotate 10s linear infinite;
filter: drop-shadow(0 0 1rem black);
fill: var(--primary-color);
}
</style>

View File

@@ -45,7 +45,6 @@ export default defineConfig({
"/login": dev_backend, "/login": dev_backend,
"/logout": dev_backend, "/logout": dev_backend,
"/zip": dev_backend, "/zip": dev_backend,
"/preview": dev_backend,
} }
}, },
build: { build: {

View File

@@ -22,7 +22,6 @@ dependencies = [
"msgspec", "msgspec",
"natsort", "natsort",
"pathvalidate", "pathvalidate",
"pillow",
"pyjwt", "pyjwt",
"sanic", "sanic",
"stream-zip", "stream-zip",
@@ -30,7 +29,7 @@ dependencies = [
] ]
[project.urls] [project.urls]
Homepage = "https://git.zi.fi/Vasanko/cista-storage" Homepage = ""
[project.scripts] [project.scripts]
cista = "cista.__main__:main" cista = "cista.__main__:main"
@@ -41,18 +40,20 @@ dev = [
"ruff", "ruff",
] ]
[tool.hatchling]
# Build frontend
pre_build = "npm run build --prefix cista-front"
[tool.hatch.version] [tool.hatch.version]
source = "vcs" source = "vcs"
[tool.hatch.build] [tool.hatch.build]
artifacts = ["cista/wwwroot"]
hooks.custom.path = "scripts/build-frontend.py"
hooks.vcs.version-file = "cista/_version.py" hooks.vcs.version-file = "cista/_version.py"
hooks.vcs.template = """ hooks.vcs.template = """
# This file is automatically generated by hatch build. # This file is automatically generated by hatch build.
__version__ = {version!r} __version__ = {version!r}
""" """
only-packages = true
targets.sdist.include = [ targets.sdist.include = [
"/cista", "/cista",
] ]

View File

@@ -1,12 +0,0 @@
# noqa: INP001
import subprocess
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
class CustomBuildHook(BuildHookInterface):
def initialize(self, version, build_data):
super().initialize(version, build_data)
print("Building Cista frontend...")
subprocess.run("npm install --prefix frontend".split(" "), check=True) # noqa: S603
subprocess.run("npm run build --prefix frontend".split(" "), check=True) # noqa: S603

View File

@@ -1,136 +0,0 @@
from pathlib import PurePosixPath
import msgspec
import pytest
from cista.protocol import FileEntry, UpdateMessage, UpdDel, UpdIns, UpdKeep
from cista.watching import State, format_update
def decode(data: str):
return msgspec.json.decode(data, type=UpdateMessage).update
# Helper function to create a list of FileEntry objects
def f(count, start=0):
return [FileEntry(i, str(i), str(i), 0, 0, 0) for i in range(start, start + count)]
def test_identical_lists():
old_list = f(3)
new_list = old_list.copy()
expected = [UpdKeep(3)]
assert decode(format_update(old_list, new_list)) == expected
def test_completely_different_lists():
old_list = f(3)
new_list = f(3, 3) # Different entries
expected = [UpdDel(3), UpdIns(new_list)]
assert decode(format_update(old_list, new_list)) == expected
def test_insertions():
old_list = f(3)
new_list = old_list[:2] + f(1, 10) + old_list[2:]
expected = [UpdKeep(2), UpdIns(f(1, 10)), UpdKeep(1)]
assert decode(format_update(old_list, new_list)) == expected
def test_deletions():
old_list = f(3)
new_list = [old_list[0], old_list[2]]
expected = [UpdKeep(1), UpdDel(1), UpdKeep(1)]
assert decode(format_update(old_list, new_list)) == expected
def test_mixed_operations():
old_list = f(4)
new_list = [old_list[0], old_list[2], *f(1, 10)]
expected = [UpdKeep(1), UpdDel(1), UpdKeep(1), UpdDel(1), UpdIns(f(1, 10))]
assert decode(format_update(old_list, new_list)) == expected
def test_empty_old_list():
old_list = []
new_list = f(3)
expected = [UpdIns(new_list)]
assert decode(format_update(old_list, new_list)) == expected
def test_empty_new_list():
old_list = f(3)
new_list = []
expected = [UpdDel(3)]
assert decode(format_update(old_list, new_list)) == expected
def test_longer_lists():
old_list = f(6)
new_list = f(1, 6) + old_list[1:3] + old_list[4:5] + f(2, 7)
expected = [
UpdDel(1),
UpdIns(f(1, 6)),
UpdKeep(2),
UpdDel(1),
UpdKeep(1),
UpdDel(1),
UpdIns(f(2, 7)),
]
assert decode(format_update(old_list, new_list)) == expected
def sortkey(name):
# Define the sorting key for names here
return name.lower()
@pytest.fixture()
def state():
entries = [
FileEntry(0, "", "root", 0, 0, 0),
FileEntry(1, "bar", "bar", 0, 0, 0),
FileEntry(2, "baz", "bar/baz", 0, 0, 0),
FileEntry(1, "foo", "foo", 0, 0, 0),
FileEntry(1, "xxx", "xxx", 0, 0, 0),
FileEntry(2, "yyy", "xxx/yyy", 0, 0, 1),
]
s = State()
s._listing = entries
return s
def test_existing_directory(state):
path = PurePosixPath("bar")
expected_slice = slice(1, 3) # Includes 'bar' and 'baz'
assert state._slice(path) == expected_slice
def test_existing_file(state):
path = PurePosixPath("xxx/yyy")
expected_slice = slice(5, 6) # Only includes 'yyy'
assert state._slice(path) == expected_slice
def test_nonexistent_directory(state):
path = PurePosixPath("zzz")
expected_slice = slice(6, 6) # 'zzz' would be inserted at end
assert state._slice(path) == expected_slice
def test_nonexistent_file(state):
path = (PurePosixPath("bar/mmm"), 1)
expected_slice = slice(3, 3) # A file would be inserted after 'baz' under 'bar'
assert state._slice(path) == expected_slice
def test_root_directory(state):
path = PurePosixPath()
expected_slice = slice(0, 6) # Entire tree
assert state._slice(path) == expected_slice
def test_directory_with_subdirs_and_files(state):
path = PurePosixPath("xxx")
expected_slice = slice(4, 6) # Includes 'xxx' and 'yyy'
assert state._slice(path) == expected_slice