diff --git a/src/lib/load/document.ts b/src/lib/load/document.ts index 9edabb460..0dcf7e1db 100644 --- a/src/lib/load/document.ts +++ b/src/lib/load/document.ts @@ -12,12 +12,13 @@ interface Load { fetch: typeof globalThis.fetch; params: { id: string }; url: URL; + depends: (key: string) => void; } /** * Load a document and its assets */ -export default async function load({ fetch, params, url }: Load) { +export default async function load({ fetch, params, url, depends }: Load) { const { data: document, error: err } = await documents.get(+params.id, fetch); if (err) { @@ -44,6 +45,8 @@ export default async function load({ fetch, params, url }: Load) { search = await documents.searchWithin(document.id, query, undefined, fetch); } + depends("document:" + params.id); + return { document, asset_url, diff --git a/src/routes/(app)/documents/[id]-[slug]/+page.ts b/src/routes/(app)/documents/[id]-[slug]/+page.ts index de51e723a..a82793f37 100644 --- a/src/routes/(app)/documents/[id]-[slug]/+page.ts +++ b/src/routes/(app)/documents/[id]-[slug]/+page.ts @@ -3,14 +3,19 @@ * We do this in a layout module because sub-routes can use the same * document without loading it again. */ -import type { ReadMode } from "@/lib/api/types"; +import type { + APIResponse, + Highlights, + Maybe, + ViewerMode, + ReadMode, +} from "$lib/api/types"; -import { redirect } from "@sveltejs/kit"; +import { redirect, error } from "@sveltejs/kit"; import { VIEWER_MAX_AGE } from "@/config/config.js"; import * as documents from "$lib/api/documents"; import { breadcrumbTrail } from "$lib/utils/index"; -import loadDocument from "$lib/load/document"; /** @type {import('./$types').PageLoad} */ export async function load({ @@ -21,11 +26,15 @@ export async function load({ url, setHeaders, }) { - const { document, asset_url, mode, search } = await loadDocument({ - fetch, - params, - url, - }); + const { data: document, error: err } = await documents.get(+params.id, fetch); + + if (err) { + return error(err.status, err.message); + } + + if (!document) { + return error(404, "Document not found"); + } depends(`document:${document.id}`); @@ -34,6 +43,22 @@ export async function load({ redirect(302, canonical.pathname); } + let mode: ViewerMode = + (url.searchParams.get("mode") as ViewerMode) ?? "document"; + const asset_url = await documents.assetUrl(document, fetch); + + if (!documents.MODES.has(mode)) { + mode = documents.MODES[0]; + } + + // If in search mode, get the query from the URL and + // initialize a Promise for the first page of search results + let search: Maybe> = undefined; + const query = url.searchParams.get("q"); + if (query) { + search = await documents.searchWithin(document.id, query, undefined, fetch); + } + if (!document.edit_access && !documents.READING_MODES.has(mode as ReadMode)) { return redirect(302, canonical); }