diff --git a/docs/navigation.md b/docs/navigation.md index 927b9740..2f83e263 100644 --- a/docs/navigation.md +++ b/docs/navigation.md @@ -1,5 +1,9 @@ # Навигация и миниатюры +Переходы выполняются внутри SPA: текущая папка остаётся на экране, пока сервер готовит следующую. Список и адрес обновляются вместе; шапка, поиск и дерево каталогов сохраняют свои компоненты. Для долгих запросов показывается тонкая полоса загрузки с задержкой 160 мс. Быстрый повторный переход отменяет предыдущий; запоздавшие ответы и ответы прежнего аккаунта не применяются. Крупные модули просмотра загружаются по необходимости до переключения страницы. + +При смене аккаунта открывается его домашняя папка, в том числе после промежуточного выхода или OAuth-перехода. Обычный повторный вход в тот же аккаунт сохраняет прямую ссылку. + Боковая панель содержит закладки и раскрывающееся дерево каталогов. Текущий путь раскрывается автоматически; для остальных папок запрашивается только непосредственное содержимое при раскрытии. Обновления текущего каталога берутся из уже загруженного списка файлов. Скрытые каталоги учитывают настройку профиля. Права и область доступа проверяются существующим API. Кнопка закладки закрепляет текущую папку. Закладки хранятся в браузере отдельно для каждого аккаунта и базового URL приложения. Крестик удаляет только закладку. Нижняя строка аккаунта открывает профиль, управление ссылками, административные разделы и выход в соответствии с правами пользователя. Меню поддерживает клавиатуру и закрывается по Escape или нажатию снаружи. diff --git a/frontend/package.json b/frontend/package.json index 1b224bc8..3fb9085a 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "filebrowser-frontend", - "version": "3.2.0", + "version": "3.2.1", "private": true, "type": "module", "engines": { diff --git a/frontend/scripts/check-internal-session.cjs b/frontend/scripts/check-internal-session.cjs index d6efe642..b19f6a12 100644 --- a/frontend/scripts/check-internal-session.cjs +++ b/frontend/scripts/check-internal-session.cjs @@ -89,6 +89,12 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE); const independent = await device2.newPage(); await independent.goto(process.env.QA_APP_ONE + "/files/"); await independent.getByText("Alice-private.txt", { exact: true }).waitFor(); + // The destination account has no such directory: switch must go home first. + await b + .locator("#listing") + .getByRole("button", { name: "Alice-only", exact: true }) + .dblclick(); + await b.getByText("nested-Alice.txt", { exact: true }).waitFor(); // Hold a valid A response until after both applications have switched to B. let release; const held = new Promise((r) => (release = r)); @@ -119,6 +125,8 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE); .waitFor({ timeout: 15000 }), ]); release(); + assert.equal(new URL(a.url()).pathname, "/files/"); + assert.equal(new URL(b.url()).pathname, "/files/"); await a.unroute("**/api/resources/"); await a.waitForTimeout(200); diff --git a/frontend/scripts/check-navigation.cjs b/frontend/scripts/check-navigation.cjs new file mode 100644 index 00000000..7b614069 --- /dev/null +++ b/frontend/scripts/check-navigation.cjs @@ -0,0 +1,243 @@ +const fs = require("node:fs"), + path = require("node:path"), + assert = require("node:assert/strict"), + { spawn } = require("node:child_process"); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE); +(async () => { + const root = fs.mkdtempSync( + path.join(process.env.FILEBROWSER_QA_OUTPUT, "navigation-") + ); + const files = path.join(root, "files"); + fs.mkdirSync(files); + fs.writeFileSync(path.join(files, "anonymous.txt"), "NO PASSWORD"); + for (const folder of ["Fast", "Slow", "Empty"]) + fs.mkdirSync(path.join(files, folder)); + fs.writeFileSync(path.join(files, "Fast", "fast.txt"), "FAST"); + fs.writeFileSync(path.join(files, "Slow", "slow.txt"), "SLOW"); + fs.mkdirSync(path.join(files, "Fast", "Nested")); + fs.writeFileSync(path.join(files, "Fast", "Nested", "nested.txt"), "NESTED"); + const config = path.join(root, "config.json"), + db = path.join(root, "test.db"); + fs.writeFileSync( + config, + JSON.stringify({ + root: files, + database: db, + sso: { issuer: "invalid-provider-configuration" }, + }) + ); + const args = [ + "--config", + config, + "--root", + files, + "--database", + db, + "--port", + "0", + ]; + const processOne = spawn(process.env.FILEBROWSER_EXE, [...args, "--no-sso"], { + cwd: root, + windowsHide: true, + stdio: ["ignore", "pipe", "pipe"], + }); + let logs = "", + browser; + const started = new Promise((resolve, reject) => { + const timeout = setTimeout( + () => reject(Error("startup timeout " + logs)), + 12000 + ); + const read = (chunk) => { + logs += chunk.toString(); + const found = logs.match(/Listening on (127\.0\.0\.1:\d+)/); + if (found) { + clearTimeout(timeout); + resolve("http://" + found[1]); + } + }; + processOne.stdout.on("data", read); + processOne.stderr.on("data", read); + processOne.once("exit", (code) => { + clearTimeout(timeout); + reject(Error("exited " + code + " " + logs)); + }); + }); + try { + const url = await started; + browser = await chromium.launch({ + executablePath: process.env.BROWSER_EXECUTABLE, + headless: true, + }); + const context = await browser.newContext(); + const page = await context.newPage(); + const errors = []; + page.on("pageerror", (error) => errors.push(String(error))); + const response = await context.request.get(url + "/api/session"); + assert.equal(response.status(), 200); + const user = await response.json(); + assert.equal(user.authMode, "no-sso"); + assert.equal(user.perm.admin, true); + await page.goto(url + "/files/"); + await page.getByText("anonymous.txt", { exact: true }).waitFor(); + assert.equal(await page.locator("iframe").count(), 0); + assert.equal(await page.locator('a[href$="/auth/account"]').count(), 0); + // Sample every rendered frame and observe removals: a single missing frame fails. + await page.evaluate(() => { + window.navNodes = [ + document.querySelector("#listing"), + document.querySelector("header"), + document.querySelector(".workspace-sidebar"), + ]; + window.navRemoved = []; + window.navBlankFrames = 0; + window.navObserver = new MutationObserver((changes) => { + for (const change of changes) + for (const removed of change.removedNodes) + for (let i = 0; i < window.navNodes.length; i++) + if ( + removed === window.navNodes[i] || + removed.contains?.(window.navNodes[i]) + ) + window.navRemoved.push(i); + }); + window.navObserver.observe(document.body, { + childList: true, + subtree: true, + }); + window.navSampling = true; + function frame() { + if (!window.navSampling) return; + if ( + !document.querySelector("#listing") || + !document.querySelector("header") + ) + window.navBlankFrames++; + requestAnimationFrame(frame); + } + requestAnimationFrame(frame); + }); + let releaseSlow; + const slowGate = new Promise((resolve) => (releaseSlow = resolve)); + await page.route("**/api/resources/Slow/", async (route) => { + await slowGate; + try { + await route.continue(); + } catch { + /* superseded request was aborted */ + } + }); + const slowRequest = page + .waitForRequest((r) => r.url().endsWith("/api/resources/Slow/")) + .catch(() => null); + await page + .locator("#listing") + .getByRole("button", { name: "Slow", exact: true }) + .dblclick(); + await slowRequest; + await page.waitForTimeout(250); + assert.equal(new URL(page.url()).pathname, "/files/"); + await page.getByText("anonymous.txt", { exact: true }).waitFor(); + assert(await page.locator(".navigation-progress").isVisible()); + await page + .locator("#listing") + .getByRole("button", { name: "Fast", exact: true }) + .dblclick(); + await page.waitForURL("**/files/Fast/"); + await page.getByText("fast.txt", { exact: true }).waitFor(); + releaseSlow(); + await page.waitForTimeout(150); + assert.equal(new URL(page.url()).pathname, "/files/Fast/"); + assert.equal(await page.getByText("slow.txt", { exact: true }).count(), 0); + await page + .locator("#listing") + .getByRole("button", { name: "Nested", exact: true }) + .dblclick(); + await page.waitForURL("**/files/Fast/Nested/"); + await page.getByText("nested.txt", { exact: true }).waitFor(); + await page.goBack(); + await page.waitForURL("**/files/Fast/"); + await page.getByText("fast.txt", { exact: true }).waitFor(); + const stability = await page.evaluate(() => { + window.navSampling = false; + window.navObserver.disconnect(); + return { + removed: window.navRemoved, + blankFrames: window.navBlankFrames, + sameNodes: window.navNodes.map((node) => document.contains(node)), + }; + }); + assert.deepEqual(stability.removed, []); + assert.equal(stability.blankFrames, 0); + assert(stability.sameNodes.every(Boolean)); + assert.equal(await page.locator(".navigation-progress").count(), 0); + await page.locator(".account-button").click(); + await page.locator('a[href="/settings/profile"]').click(); + await page.waitForURL("**/settings/profile"); + await page.locator(".settings-page").waitFor(); + assert(await page.evaluate(() => document.contains(window.navNodes[2]))); + await page.goBack(); + await page.waitForURL("**/files/Fast/"); + await page.getByText("fast.txt", { exact: true }).waitFor(); + // The same workspace works on a phone, including an empty directory and back. + await page.setViewportSize({ width: 390, height: 844 }); + await page.goBack(); + await page.waitForURL("**/files/"); + await page + .locator("#listing") + .getByRole("button", { name: "Empty", exact: true }) + .dblclick(); + await page.waitForURL("**/files/Empty/"); + await page.locator(".message").waitFor(); + assert( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth + ) + ); + await page.goBack(); + await page.waitForURL("**/files/"); + await page.getByText("anonymous.txt", { exact: true }).waitFor(); + // Preview entry and return are client-side transitions too. + await page + .getByRole("button", { name: "anonymous.txt", exact: true }) + .dblclick(); + await page.waitForURL("**/files/anonymous.txt"); + await page.locator("#previewer").waitFor(); + await page.goBack(); + await page.waitForURL("**/files/"); + await page.getByText("anonymous.txt", { exact: true }).waitFor(); + assert.equal( + await page.evaluate( + () => performance.getEntriesByType("navigation").length + ), + 1 + ); + assert.deepEqual(errors, []); + await page.screenshot({ path: path.join(root, "mobile-navigation.png") }); + console.log( + "Atomic SPA navigation: persistent listing/header/sidebar; zero blank frames; slow and superseded requests; nested/back/empty/mobile/preview passed." + ); + } catch (error) { + if (browser) { + for (const ctx of browser.contexts()) + for (const tab of ctx.pages()) { + fs.writeFileSync( + path.join(root, "failure.html"), + await tab.content() + ); + await tab.screenshot({ path: path.join(root, "failure.png") }); + } + } + throw error; + } finally { + if (browser) await browser.close(); + if (processOne.exitCode === null) { + processOne.kill(); + await new Promise((r) => processOne.once("exit", r)); + } + fs.writeFileSync(path.join(root, "server.log"), logs); + } +})().catch((e) => { + console.error(e); + process.exitCode = 1; +}); diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 19b21a0a..6cf77cfa 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,7 +1,14 @@ {{ name }} - + + {{ $t("files.loading") }} + + @@ -23,16 +30,16 @@ const auth = useAuthStore(), route = useRoute(), router = useRouter(); watch( - () => auth.user?.id, - (id, old) => { - if (id && old && id !== old && route.meta.requiresAuth) - void router.replace("/files/"); + () => auth.accountChanged, + (changed) => { + if (changed && route.meta.requiresAuth) + void router.replace({ path: "/files/", force: true }); } ); watch( () => auth.user?.perm.admin, (admin) => { - if (admin === false && route.meta.requiresAdmin) + if (admin === false && !auth.accountChanged && route.meta.requiresAdmin) void router.replace("/403"); } ); diff --git a/frontend/src/css/workspace.css b/frontend/src/css/workspace.css index f2b3efb9..7a87e2ea 100644 --- a/frontend/src/css/workspace.css +++ b/frontend/src/css/workspace.css @@ -974,3 +974,47 @@ select:focus { border-radius: 8px; background: var(--surfaceSecondary); } +.navigation-progress { + position: fixed; + z-index: 2000; + top: calc(4em - 2px); + inset-inline: 0; + height: 2px; + overflow: hidden; + pointer-events: none; + animation: navigation-reveal 160ms step-end both; +} + +.navigation-progress::after { + content: ""; + display: block; + width: 35%; + height: 100%; + background: var(--blue); + animation: navigation-slide 1.2s ease-in-out infinite; +} + +@keyframes navigation-reveal { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes navigation-slide { + from { + transform: translateX(-100%); + } + to { + transform: translateX(390%); + } +} + +@media (prefers-reduced-motion: reduce) { + .navigation-progress::after { + width: 100%; + animation: none; + } +} diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 4ef567e3..864af269 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -14,6 +14,7 @@ import { useAuthStore } from "@/stores/auth"; import { baseURL, name } from "@/utils/constants"; import i18n from "@/i18n"; import { validateLogin } from "@/utils/auth"; +import { installResourceNavigation } from "@/utils/resource-navigation"; const titles = { CraftEditor: "addons.title", @@ -203,6 +204,9 @@ router.beforeResolve(async (to, from) => { }; } + if (authStore.accountChanged && to.path !== "/files/") + return { path: "/files/" }; + if (to.matched.some((record) => record.meta.requiresAdmin)) { if (authStore.user === null || !authStore.user.perm.admin) { return { path: "/403" }; @@ -213,4 +217,11 @@ router.beforeResolve(async (to, from) => { return; }); +installResourceNavigation(router); + +router.afterEach((to, _from, failure) => { + if (!failure && to.name === "Files" && to.path === "/files/") + useAuthStore().accountChanged = false; +}); + export { router, router as default }; diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts index 6998075d..c4e0b387 100644 --- a/frontend/src/stores/auth.ts +++ b/frontend/src/stores/auth.ts @@ -11,6 +11,7 @@ export const useAuthStore = defineStore("auth", { sessionState: string; requiredFactors: string[]; epoch: number; + accountChanged: boolean; } => ({ user: null, logoutTimer: null, @@ -18,6 +19,7 @@ export const useAuthStore = defineStore("auth", { sessionState: "", requiredFactors: [], epoch: 0, + accountChanged: false, }), getters: { isLoggedIn: (state) => state.user !== null, diff --git a/frontend/src/stores/file.ts b/frontend/src/stores/file.ts index 6ffe35d6..f743f0f1 100644 --- a/frontend/src/stores/file.ts +++ b/frontend/src/stores/file.ts @@ -10,6 +10,7 @@ export const useFileStore = defineStore("file", { multiple: boolean; isFiles: boolean; preselect: string | null; + requestError: number | null; } => ({ req: null, oldReq: null, @@ -18,6 +19,7 @@ export const useFileStore = defineStore("file", { multiple: false, isFiles: false, preselect: null, + requestError: null, }), getters: { selectedCount: (state) => state.selected.length, diff --git a/frontend/src/utils/__tests__/account-switch.test.ts b/frontend/src/utils/__tests__/account-switch.test.ts new file mode 100644 index 00000000..31bbb3c3 --- /dev/null +++ b/frontend/src/utils/__tests__/account-switch.test.ts @@ -0,0 +1,63 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + auth: { + user: null as IUser | null, + epoch: 0, + sessionStatus: "checking", + sessionState: "", + requiredFactors: [] as string[], + accountChanged: false, + setUser(user: IUser) { + this.user = user; + }, + }, +})); +vi.mock("@/stores/auth", () => ({ useAuthStore: () => mocks.auth })); +vi.mock("@/stores/upload", () => ({ + useUploadStore: () => ({ resetForAccount: vi.fn() }), +})); +vi.mock("@/stores", () => ({ resetAccountStores: vi.fn() })); +vi.mock("../constants", () => ({ baseURL: "" })); +const profile = (id: number) => ({ + status: "authenticated", + authenticated: true, + session_state: String(id), + user: { id, perm: { admin: false } } as IUser, +}); + +describe("account switch destination", () => { + beforeEach(() => { + vi.resetModules(); + mocks.auth.user = null; + mocks.auth.accountChanged = false; + const storage = new Map(); + vi.stubGlobal("sessionStorage", { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => storage.set(key, value), + }); + vi.stubGlobal("window", { dispatchEvent: vi.fn() }); + }); + + it("preserves a first deep link and a same-account session refresh", async () => { + const { acceptSession } = await import("../auth"); + acceptSession(profile(1)); + acceptSession({ ...profile(1), session_state: "new-version" }); + expect(mocks.auth.accountChanged).toBe(false); + }); + + it("requests home when A changes to B through a signed-out state", async () => { + const { acceptSession } = await import("../auth"); + acceptSession(profile(1)); + acceptSession({ status: "signed_out", authenticated: false }); + acceptSession(profile(2)); + expect(mocks.auth.accountChanged).toBe(true); + }); + + it("detects an account changed across an OAuth page reload", async () => { + (await import("../auth")).acceptSession(profile(1)); + vi.resetModules(); + (await import("../auth")).acceptSession(profile(2)); + expect(mocks.auth.accountChanged).toBe(true); + }); +}); diff --git a/frontend/src/utils/__tests__/resource-navigation.test.ts b/frontend/src/utils/__tests__/resource-navigation.test.ts new file mode 100644 index 00000000..d2eea1af --- /dev/null +++ b/frontend/src/utils/__tests__/resource-navigation.test.ts @@ -0,0 +1,166 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { Router } from "vue-router"; +import { installResourceNavigation } from "../resource-navigation"; +import { changeSessionScope } from "../session-scope"; +import { StatusError } from "@/api/utils"; + +const mocks = vi.hoisted(() => ({ + fetch: vi.fn(), + file: { + selected: [1], + multiple: false, + reload: false, + requestError: null as number | null, + updateRequest: vi.fn(), + }, + layout: { loading: false }, +})); +vi.mock("@/api", () => ({ files: { fetch: mocks.fetch } })); +vi.mock("@/api/utils", () => ({ + StatusError: class extends Error { + constructor( + public message: string, + public status: number, + public is_canceled = false + ) { + super(message); + } + }, +})); +vi.mock("@/stores/file", () => ({ useFileStore: () => mocks.file })); +vi.mock("@/stores/layout", () => ({ useLayoutStore: () => mocks.layout })); + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => (resolve = done)); + return { promise, resolve }; +} +function harness() { + const hooks: Record any> = {}; + const router = Object.fromEntries( + ["beforeEach", "beforeResolve", "afterEach", "onError"].map((key) => [ + key, + (callback: (...args: any[]) => any) => (hooks[key] = callback), + ]) + ); + installResourceNavigation(router as unknown as Router); + return hooks; +} +const destination = (name: string) => ({ + name: "Files", + path: `/files/${name}/`, + fullPath: `/files/${name}/`, + query: {}, +}); +const directory = { isDir: true } as Resource; + +describe("atomic workspace navigation", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.layout.loading = false; + mocks.file.requestError = null; + changeSessionScope("test-account", "current"); + }); + + it("keeps the old resource until the router commits the prepared destination", async () => { + const hooks = harness(), + pending = deferred(), + to = destination("next"); + mocks.fetch.mockReturnValue(pending.promise); + hooks.beforeEach(); + const navigation = hooks.beforeResolve(to); + expect(mocks.layout.loading).toBe(true); + expect(mocks.file.updateRequest).not.toHaveBeenCalled(); + pending.resolve(directory); + await navigation; + expect(mocks.file.updateRequest).not.toHaveBeenCalled(); + hooks.afterEach(to, {}, undefined); + expect(mocks.file.updateRequest).toHaveBeenCalledExactlyOnceWith(directory); + expect(mocks.layout.loading).toBe(false); + }); + + it("aborts superseded navigation and rejects late results even if fetch ignores abort", async () => { + const hooks = harness(), + first = deferred(), + second = deferred(); + mocks.fetch + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise); + hooks.beforeEach(); + const oldDestination = destination("old"); + const newDestination = destination("new"); + const old = hooks.beforeResolve(oldDestination); + const oldSignal = mocks.fetch.mock.calls[0][1] as AbortSignal; + hooks.beforeEach(); + const next = hooks.beforeResolve(newDestination); + expect(oldSignal.aborted).toBe(true); + first.resolve(directory); + expect(await old).toBe(false); + hooks.afterEach(oldDestination, {}, Error("cancelled")); + expect(mocks.layout.loading).toBe(true); + second.resolve(directory); + await next; + hooks.afterEach(newDestination, {}, undefined); + expect(mocks.file.updateRequest).toHaveBeenCalledTimes(1); + }); + + it("a cancelled transition to the same URL cannot cancel its newer replacement", async () => { + const hooks = harness(), + first = deferred(), + second = deferred(); + const oldDestination = destination("home"), + newDestination = destination("home"); + mocks.fetch + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise); + hooks.beforeEach(); + const old = hooks.beforeResolve(oldDestination); + hooks.beforeEach(); + const next = hooks.beforeResolve(newDestination); + first.resolve(directory); + expect(await old).toBe(false); + hooks.afterEach(oldDestination, {}, Error("cancelled")); + expect(mocks.layout.loading).toBe(true); + second.resolve(directory); + await next; + hooks.afterEach(newDestination, {}, undefined); + expect(mocks.file.updateRequest).toHaveBeenCalledExactlyOnceWith(directory); + }); + + it("never commits a response from a previous account", async () => { + const hooks = harness(), + to = destination("private"); + mocks.fetch.mockResolvedValue(directory); + hooks.beforeEach(); + await hooks.beforeResolve(to); + changeSessionScope("another-account", "new-state"); + hooks.afterEach(to, {}, undefined); + expect(mocks.file.updateRequest).not.toHaveBeenCalled(); + }); + + it.each([0, 404])( + "commits error %s with its destination without clearing the old page while loading", + async (status) => { + const hooks = harness(), + to = destination("missing"); + mocks.fetch.mockRejectedValue(new StatusError("Missing", status)); + hooks.beforeEach(); + await hooks.beforeResolve(to); + expect(mocks.file.updateRequest).not.toHaveBeenCalled(); + hooks.afterEach(to, {}, undefined); + expect(mocks.file.requestError).toBe(status); + expect(mocks.file.updateRequest).toHaveBeenCalledWith(null); + } + ); + + it("does not replace the workspace when a later guard cancels the transition", async () => { + const hooks = harness(), + to = destination("cancelled"); + mocks.fetch.mockResolvedValue(directory); + hooks.beforeEach(); + await hooks.beforeResolve(to); + hooks.afterEach(to, {}, Error("cancelled")); + expect(mocks.file.updateRequest).not.toHaveBeenCalled(); + expect(mocks.layout.loading).toBe(false); + }); +}); diff --git a/frontend/src/utils/auth.ts b/frontend/src/utils/auth.ts index 5375a0f0..e904ae50 100644 --- a/frontend/src/utils/auth.ts +++ b/frontend/src/utils/auth.ts @@ -10,6 +10,24 @@ export interface SessionState { user?: IUser; required_factors?: string[]; } +let lastAccount: string | undefined; +function rememberAccount(id: number | string) { + const key = `filebrowser:${baseURL}:last-account`; + // Keep the previous identity through signed-out/factor states and an OAuth reload. + try { + lastAccount ??= sessionStorage.getItem(key) || undefined; + } catch { + /* In-memory tracking still works when browser storage is unavailable. */ + } + const changed = lastAccount !== undefined && lastAccount !== String(id); + lastAccount = String(id); + try { + sessionStorage.setItem(key, lastAccount); + } catch { + /* Storage is optional. */ + } + return changed; +} export function startLogin( target = window.location.pathname + window.location.search, silent = false @@ -30,6 +48,7 @@ export function acceptSession(state: SessionState) { const next = valid ? `${state.user!.id}:${state.session_state}:${JSON.stringify(state.user!.perm)}` : state.status; + if (valid && rememberAccount(state.user!.id)) auth.accountChanged = true; if (changeSessionScope(next, state.session_state || "")) { // Hide the old account before any new identity or data can be rendered. auth.user = null; diff --git a/frontend/src/utils/resource-navigation.ts b/frontend/src/utils/resource-navigation.ts new file mode 100644 index 00000000..e47c311a --- /dev/null +++ b/frontend/src/utils/resource-navigation.ts @@ -0,0 +1,85 @@ +import type { Router, RouteLocationNormalized } from "vue-router"; +import { files } from "@/api"; +import { StatusError } from "@/api/utils"; +import { useFileStore } from "@/stores/file"; +import { useLayoutStore } from "@/stores/layout"; +import { sessionScope, sessionIsCurrent } from "./session-scope"; + +// Prepare the destination while the current route and its DOM remain usable. +// Commit the resource and route together, never old files under a new URL. +export function installResourceNavigation(router: Router) { + let current: + | { + controller: AbortController; + destination: RouteLocationNormalized; + scope: ReturnType; + resource?: Resource; + error?: number; + } + | undefined; + + router.beforeEach(() => { + current?.controller.abort(); + current = undefined; + useLayoutStore().loading = false; + }); + + router.beforeResolve(async (to) => { + if (to.name !== "Files") return; + const request = { + controller: new AbortController(), + destination: to, + scope: sessionScope(), + } as NonNullable; + current = request; + useLayoutStore().loading = true; + try { + request.resource = await files.fetch(to.path, request.controller.signal); + if ( + request.controller.signal.aborted || + !sessionIsCurrent(request.scope.generation) + ) + return false; + if (!request.resource.isDir) { + // Resolve the viewer chunk before replacing the current workspace. + if (to.query.craft) await import("@/views/files/CraftEditor.vue"); + else if (to.query.edit === "true") + await import("@/views/files/Editor.vue"); + else await import("@/views/files/Preview.vue"); + } + } catch (error) { + if ( + request.controller.signal.aborted || + !sessionIsCurrent(request.scope.generation) || + (error instanceof StatusError && error.is_canceled) + ) + return false; + request.error = + error instanceof StatusError ? (error.status ?? 500) : 500; + } + if (current !== request || request.controller.signal.aborted) return false; + }); + + router.afterEach((to, _from, failure) => { + const request = current; + if (!request || request.destination !== to) return; + if (!failure && sessionIsCurrent(request.scope.generation)) { + const file = useFileStore(); + file.selected = []; + file.multiple = false; + file.reload = false; + file.requestError = request.error ?? null; + file.updateRequest( + request.error !== undefined ? null : (request.resource ?? null) + ); + } + current = undefined; + useLayoutStore().loading = false; + }); + router.onError((_error, to) => { + if (current?.destination !== to) return; + current?.controller.abort(); + current = undefined; + useLayoutStore().loading = false; + }); +} diff --git a/frontend/src/views/Files.vue b/frontend/src/views/Files.vue index 2c9cd031..4923628c 100644 --- a/frontend/src/views/Files.vue +++ b/frontend/src/views/Files.vue @@ -1,16 +1,16 @@ - + @@ -32,7 +32,6 @@ import { onBeforeUnmount, onMounted, onUnmounted, - ref, watch, } from "vue"; import { files as api } from "@/api"; @@ -43,10 +42,11 @@ import { useLayoutStore } from "@/stores/layout"; import HeaderBar from "@/components/header/HeaderBar.vue"; import Errors from "@/views/Errors.vue"; import { useI18n } from "vue-i18n"; -import { useRoute } from "vue-router"; +import { useRoute, onBeforeRouteUpdate, onBeforeRouteLeave } from "vue-router"; import FileListing from "@/views/files/FileListing.vue"; import { StatusError } from "@/api/utils"; import { name } from "../utils/constants"; +import { sessionScope, sessionIsCurrent } from "@/utils/session-scope"; const Editor = defineAsyncComponent(() => import("@/views/files/Editor.vue")); const Preview = defineAsyncComponent(() => import("@/views/files/Preview.vue")); @@ -65,10 +65,9 @@ const { t } = useI18n({}); let fetchDataController = new AbortController(); -const error = ref(null); +const error = computed(() => fileStore.requestError); const currentView = computed(() => { - if (route.query.craft && layoutStore.loading) return null; if (fileStore.req?.type === undefined) { return null; } @@ -102,8 +101,11 @@ const currentView = computed(() => { // Define hooks onMounted(() => { - fetchData(); fileStore.isFiles = true; + // Account changes remount this view without a route navigation. + if (!fileStore.req && !fileStore.requestError) void fetchData(); + else if (fileStore.req) + document.title = `${fileStore.req.name || t("sidebar.myFiles")} - ${t("files.files")} - ${name}`; window.addEventListener("keydown", keyEvent); }); @@ -120,9 +122,17 @@ onUnmounted(() => { fetchDataController.abort(); }); -watch(route, () => { - fetchData(); -}); +// The router has already prepared and committed the destination resource. +watch( + () => fileStore.req, + (res) => { + if (!res) return; + document.title = `${res.name || t("sidebar.myFiles")} - ${t("files.files")} - ${name}`; + applyPreSelection(); + } +); +onBeforeRouteUpdate(() => fetchDataController.abort()); +onBeforeRouteLeave(() => fetchDataController.abort()); watch(reload, (newValue) => { if (newValue && route.query.craft) { fileStore.reload = false; @@ -168,7 +178,7 @@ const fetchData = async () => { // Set loading to true and reset the error. layoutStore.loading = true; - error.value = null; + fileStore.requestError = null; let url = route.path; if (url === "") url = "/"; @@ -176,21 +186,24 @@ const fetchData = async () => { // Cancel the ongoing request fetchDataController.abort(); fetchDataController = new AbortController(); + const request = fetchDataController; + const scope = sessionScope(); try { - const res = await api.fetch(url, fetchDataController.signal); + const res = await api.fetch(url, request.signal); + if (request.signal.aborted || !sessionIsCurrent(scope.generation)) return; fileStore.updateRequest(res); document.title = `${res.name || t("sidebar.myFiles")} - ${t("files.files")} - ${name}`; layoutStore.loading = false; - - // Selects the post-reload target item or the previously visited child folder - applyPreSelection(); } catch (err) { - if (err instanceof StatusError && err.is_canceled) { + if ( + request.signal.aborted || + !sessionIsCurrent(scope.generation) || + (err instanceof StatusError && err.is_canceled) + ) { return; } - if (err instanceof Error) { - error.value = err; - } + fileStore.requestError = + err instanceof StatusError ? (err.status ?? 500) : 500; layoutStore.loading = false; } }; diff --git a/frontend/src/views/Layout.vue b/frontend/src/views/Layout.vue index c8ffd3d4..1b871dbd 100644 --- a/frontend/src/views/Layout.vue +++ b/frontend/src/views/Layout.vue @@ -1,5 +1,11 @@ + - - - - - - - + diff --git a/frontend/src/views/files/FileListing.vue b/frontend/src/views/files/FileListing.vue index c4bd3b83..13b0e9e7 100644 --- a/frontend/src/views/files/FileListing.vue +++ b/frontend/src/views/files/FileListing.vue @@ -13,17 +13,7 @@ - - - - - - - - {{ t("files.loading") }} - - - + { document.removeEventListener("drop", drop); }); -const base64 = (name: string) => Base64.encodeURI(name); - const keyEvent = (event: KeyboardEvent) => { // No prompts are shown if (layoutStore.currentPrompt !== null) { diff --git a/frontend/src/views/files/Preview.vue b/frontend/src/views/files/Preview.vue index 85bf028a..aaf29450 100644 --- a/frontend/src/views/files/Preview.vue +++ b/frontend/src/views/files/Preview.vue @@ -62,14 +62,7 @@ - - - - - - - - +